NeunNatter
NeunNatter

Reputation: 87

How to find a certain XML-Element and add it as a new one?

Hi I looped through an XML Document and searching for specific Word (that works) and after that i would like to a a certain Element if the word is included in that part.

<product>
    <title>TestProduct</title>
    <Specifications>
      <item name="Specifications1">Test</item>
      <item name="Specifications2">Hello World</item>
    </Specifications>
    <body>
      <item name="Color">Black</item>
    </body>
 </product>

I tried this:

<?php

$dom = new DOMDocument;
$dom->load('Test.xml');
# set up the xpath
$xpath = new DOMXPath($dom);
$append= $dom->getElementsByTagName('Text');
print_r($append);
foreach ($xpath->query("*[contains(., 'Test')]") as $item) {
    $element = $dom->createElement('ID', '123');
    $append->appendChild($element);
}    
?>

but it doesn't work can someone give me a hint? Tanks ;)

Upvotes: 0

Views: 40

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57121

The problem is that your trying to add the new element into the wrong place. This combines the getElementsByTagName and the XPath into one loop and then adds the new element to any element it finds.

$dom = new DOMDocument;
$dom->load('Test.xml');
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//*[contains(., 'Black')]") as $item) {
    $element = $dom->createElement('ID', '123');
    $item->appendChild($element);
}

echo $dom->saveXML();

See how the XPath finds any element which contains 'Test'. Then it adds the new element to each element it finds. The main thing that I have changed is you were adding the ID to $append and not $item.

If you wanted to just update the first instance of a particular piece of text...

$matchList = $xpath->query("//*[contains(text(), 'Black')]");
$element = $dom->createElement('ID', '123');
$matchList->item(0)->appendChild($element);
echo $dom->saveXML().PHP_EOL;

Upvotes: 1

Related Questions