0

I've got a problem editing an xml file by php. This is my xml, I used DOM to create it:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <node1/>
  <node2>
    <child id="child1">
      <subchild1/>
      <subchild2/>
    </child>
    <child id="child2">
      <subchild1/>
      <subchild2/>
    </child>
    <child id="child3">
      <subchild1/>
      <subchild2/>
    </child>
  </node2>
</root>

I have to insert text in nodes by id, I'll insert ids for subchilds later... so I used that code:

$dom = new DOMDocument();
         $dom->load('documento.xml');
       $library = $dom->documentElement;
       $xpath = new DOMXPath($dom);
       $result = $xpath->query('/root/node2/child[@id="child1"]');
       $result->item(0)->nodeValue .= "text";

It worked but it deleted subchild1 and subchild2, so now I've got this, with the space that you can see there:

<?xml version="1.0" encoding="UTF-8"?>
    <root>
      <node1/>
      <node2>
        <child id="child1">


        text</child>
        <child id="child2">
          <subchild1/>
          <subchild2/>
        </child>
        <child id="child3">
          <subchild1/>
          <subchild2/>
        </child>
      </node2>
    </root>

Why subchilds were deleted??

Mark
  • 141
  • 1
  • 3
  • 15
  • First thing, using XPath to reach an element by id is overkill since you can use `DOMDocument::getElementById` (an id is unique, so you don't need to describe any path). Do you want to insert text before subchilds elements or after? – Casimir et Hippolyte Feb 02 '16 at 15:18
  • @CasimiretHippolyte I tryied to use it but I wasn't able to make it works because it returns null – Mark Feb 02 '16 at 15:22
  • Possible duplicate of [How to modify xml file using PHP](http://stackoverflow.com/questions/1193528/how-to-modify-xml-file-using-php) – michi Feb 02 '16 at 22:01
  • @CasimiretHippolyte sorry I saw your edit just now, I've solved, I forgot to add /subchild1 in xpath query, now it works! – Mark Feb 03 '16 at 06:31

0 Answers0