简体   繁体   中英

using PHP to edit xml - insert after last

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

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>

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