简体   繁体   中英

PHP: Find XML node and insert child

I have an xml document with the following structure:

<?xml version="1.0" encoding="UTF-8"?>
<items>
  <item>
    <id>1</id>
    <url>www.test.com</url>
  </item>
  <item>
    <id>2</id>
    <url>www.test2.com</url>
  </item>
</items>

I would like to be able to search for a node value, such as the value of 1 for the id field. Then, once that node is found, select the parent node, which would be < item > and insert a new child within.

I know the concept of using dom document, but not sure how to do it in this instance.

This should be a start:

$dom = new DOMDocument;
$dom->loadXML($input);
$ids = $dom->getElementsByTagName('id');
foreach ($ids as $id) {
  if ($id->nodeValue == '1') {
    $child = $dom->createElement('tagname');
    $child->appendChild($dom->createTextNode('some text'));
    $id->parentNode->appendChild($child);
  }
}
$xml = $dom->saveXML();

or something close to it.

You can do the same thing in a simpler way. Instead of looking for an <id/> node whose value is 1 then selecting its parent, you can reverse the relation and look for any node which has an <id/> child whose value is 1 .

You can do that very easily in XPath, and here's how to do it in SimpleXML:

$items = simplexml_load_string(
    '<?xml version="1.0" encoding="UTF-8"?>
    <items>
      <item>
        <id>1</id>
        <url>www.test.com</url>
      </item>
      <item>
        <id>2</id>
        <url>www.test2.com</url>
      </item>
    </items>'
);

$nodes = $items->xpath('*[id = "1"]');
$nodes[0]->addChild('new', 'value');

echo $items->asXML();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM