using PHP to edit xml - insert after last

137 Views Asked by At

So i have this code that is generated mostly by answers for questions asked here. I want to add a new after the last one existing. this is my xml code example (with a lot of Placemarks):

 <Folder>
  <Placemark>
    <name><![CDATA[scscsc]]></name>
    <description><![CDATA[Description:ascasc<c,ascascasc<br>]]></description>
    <styleUrl>#placemark-brown</styleUrl>
    <ExtendedData>
    </ExtendedData>
    <Point>
      <coordinates>24.069631625000056,-23.784080251008078,0</coordinates>
    </Point>
   </Placemark>
 </Folder>

what i currently have in php is to insert the new one before the last one, and i want it after the last one. php code:

    // find the Folder tag
$root = $xmldoc->getElementsByTagName('Folder')->item(0);

// create the <placemark> tag
$placemark = $xmldoc->createElement('Placemark');

// add the placemark tag After the last element in the <Folder> tag
$root->insertBefore( $placemark, $root->lastChild );
1

There are 1 best solutions below

1
On BEST ANSWER

I'm not sure if I'm missing what you mean, but it worked as expected for me?

Looking at the docs "The reference node. If not supplied, newnode is appended to the children."

So, although it was appending for me anyway, maybe just omit the second parameter?

$root->insertBefore( $placemark );

(Saved your xml into file.xml)

$xmldoc = new DOMDocument();
$xmldoc->load("file.xml");

// find the Folder tag
$root = $xmldoc->getElementsByTagName('Folder')->item(0);

// create the <placemark> tag
$placemark = $xmldoc->createElement('Placemark');

// add the placemark tag After the last element in the <Folder> tag
$root->insertBefore( $placemark );

$xmldoc->save('file.xml', LIBXML_NOEMPTYTAG);

Which output the following

    <?xml version="1.0"?>
    <Folder>
    <Placemark>
        <name><![CDATA[scscsc]]></name>
        <description><![CDATA[Description:ascasc<c,ascascasc<br>]]></description>
        <styleUrl>#placemark-brown</styleUrl>
        <ExtendedData>
        </ExtendedData>
        <Point>
        <coordinates>24.069631625000056,-23.784080251008078,0</coordinates>
        </Point>
    </Placemark>
    <Placemark></Placemark>
    </Folder>