X
X
xFRAPS2018-08-20 14:27:27
PHP
xFRAPS, 2018-08-20 14:27:27

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

1 answer(s)
B
bears, 2018-08-20
@xFRAPS

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();

Working example
But if the work is more global, then it is better to use ready-made libraries, for example DomCrawler

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question