How to modify xml file using PHP

前端 未结 3 841
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 16:59

I want to modify my xml file in PHP based on the following criteria.

my xml structure look like this:



        
3条回答
  •  再見小時候
    2020-11-27 17:58

    You can use the DOMDocument from PHP.

    You load your file and than loop trough the childNodes of the document.

    load("file.xml");
    
    $root=$dom->documentElement; // This can differ (I am not sure, it can be only documentElement or documentElement->firstChild or only firstChild)
    
    $nodesToDelete=array();
    
    $markers=$root->getElementsByTagName('marker');
    
    // Loop trough childNodes
    foreach ($markers as $marker) {
        $type=$marker->getElementsByTagName('type')->item(0)->textContent;
        $title=$marker->getElementsByTagName('title')->item(0)->textContent;
        $address=$marker->getElementsByTagName('address')->item(0)->textContent;
        $latitude=$marker->getElementsByTagName('latitude')->item(0)->textContent;
        $longitude=$marker->getElementsByTagName('longitude')->item(0)->textContent;
    
        // Your filters here
    
        // To remove the marker you just add it to a list of nodes to delete
        $nodesToDelete[]=$marker;
    }
    
    // You delete the nodes
    foreach ($nodesToDelete as $node) $node->parentNode->removeChild($node);
    
    echo $dom->saveXML();
    ?>
    

    You can save your output XML like this

    $dom->saveXML(); // This will return the XML as a string
    $dom->save('file.xml'); // This saves the XML to a file
    

    To do this parsing in JavaScript you should use jQuery (a small, but powerful library).

    You can include the library directly from Google Code Repository.

    
    

    The library is cross-browser and very small. It should be cached in many cases, because some sites use it from Google Code

    $(yourXMLStringOrDocument).find("marker").each(function () {
         var marker=$(this);
    
         var type=marker.find('type').text();
         var title=marker.find('title').text();
         var address=marker.find('address').text();
         var latitude=marker.find('latitude').text();
         var longitude=marker.find('longitude').text();
    });
    

提交回复
热议问题