Answer the question
In order to leave comments, you need to log in
How to use xPath to replace?
Good afternoon!
You need to replace picture with picture1, picture2, picture3... inside the XML file and output the entire XML.
XML:
<offers>
<offer id="1" available="true">
<url>
http://localhost.com/
</url>
<name>Название</name>
<picture>
http://localhost.com/pic1.png
</picture>
<picture>
http://localhost.com/pic2.png
</picture>
</offer>
</offers>
<offer id="2" available="true">
<url>
http://localhost.com/
</url>
<name>Название</name>
<picture>
http://localhost.com/pic3.png
</picture>
<picture>
http://localhost.com/pic4.png
</picture>
</offer>
</offers>
Answer the question
In order to leave comments, you need to log in
For example like this:
$string = <<<XML
<offers>
<offer id="1" available="true">
<url>
http://localhost.com/
</url>
<name>Название</name>
<picture>
http://localhost.com/pic1.png
</picture>
<picture>
http://localhost.com/pic2.png
</picture>
</offer>
<offer id="2" available="true">
<url>
http://localhost.com/
</url>
<name>Название</name>
<picture>
http://localhost.com/pic3.png
</picture>
<picture>
http://localhost.com/pic4.png
</picture>
<picture>
http://localhost.com/pic5.png
</picture>
</offer>
</offers>
XML;
$dom = new DOMDocument();
$dom->loadXML($string);
$domXpath = new DOMXpath($dom);
for ($i = 0; $i < $dom->getElementsByTagName('offer')->length; $i++) {
$xpath = sprintf('//offer[%d]/picture', $i + 1);
$pics = [];
$pictures = $domXpath->query($xpath);
foreach ($pictures as $k => $picture) {
$pics[] = trim($picture->nodeValue);
if ($k > 0) {
$picture->parentNode->removeChild($picture);
}
}
if ($pictures->length > 0) {
$pictures->item(0)->nodeValue = implode(' | ', $pics);
}
}
echo $dom->saveXML();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question