Hello!
I have an XML file, and I want to insert new nodes, but I don't know how?
Can somebody help me?

This is my XML file.

<?xml version="1.0" encoding="utf-8"?>
<root>
<uri><![CDATA[http://api.bart.gov/api/route.aspx?cmd=routeinfo&route=2]]></uri>
<sched_num>28</sched_num>
<routes>
<route>
<name>Millbrae/SFIA - Pittsburg/Bay Point</name>
<abbr>SFIA-PITT</abbr>
<config>
<station>MLBR</station>
<station>SFIA</station>
<station>SBRN</station>
</config>
</route>
</routes>
<message/>
</root>

Now I have new route, which I want to add to this file, How I can do that?

$newroute =

<?xml version="1.0" encoding="utf-8"?>
<root>
<uri><![CDATA[http://api.bart.gov/api/route.aspx?cmd=routeinfo&route=3]]></uri>
<sched_num>28</sched_num>
<routes>
<route>
<name>Richmond - Fremont</name>
<abbr>RICH-FRMY</abbr>
<config>
<station>MLBR</station>
<station>SFIA</station>
<station>SBRN</station>
</config>
</route>
</routes>
<message/>
</root>

Thx a lot!

    5 days later

    I've only just recently done this myself using SimpleXML.

    // I made an instance of SimpleXMLElement from the existing XML string
    $xml = new SimpleXMLElement($originalXml);
    // then knowing which node is needed, grab it
    $node = $xml->{'routes'};
    // now you can start adding child nodes under routes
    $route = $node->addChild('route');
    // and add the other elements as children of $route, etc
    

    In the end you'll have new XML document you can get by $xml->asXML();

    I went pretty fast here, so I made have made a mistake. Also, if ordering of route elements matters you'll have to do more work.

    One more note: if this file is going to be very big you may have to resort to a different method, like a more line-by-line style of XML processing. How big is very big? I don't know. For my own project the XML file will never be more than 1K, so I'm not worried.

      Write a Reply...