adding a new node in XML file via PHP

后端 未结 3 1309
我在风中等你
我在风中等你 2020-12-29 16:30

I just wanted to ask a question .. how can i insert a new node in an xml using php. my XML file (questions.xml) is given below



        
3条回答
  •  無奈伤痛
    2020-12-29 16:47

    The best and safe way is to load your XML document into a PHP DOMDocument object, and then go to your desired node, add a child, and finally save the new version of the XML into a file.

    Take a look at the documentation : DOMDocument

    Example of code:

    // open and load a XML file
    $dom = new DomDocument();
    $dom->load('your_file.xml');
    
    // Apply some modification
    $specificNode = $dom->getElementsByTagName('node_to_catch');
    $newSubTopic = $xmldoc->createElement('subtopic');
    $newSubTopicText = $xmldoc->createTextNode('geography');
    $newSubTopic->appendChild($newSubTopicText);
    $specificNode->appendChild($newSubTopic);
    
    // Save the new version of the file
    $dom->save('your_file_v2.xml');
    

提交回复
热议问题