Updating XML node with PHP

前端 未结 3 1350
说谎
说谎 2020-11-29 08:40

I\'ve an XML file test.xml



  
    
      FirstName
             


        
相关标签:
3条回答
  • 2020-11-29 09:14

    You're not accessing the right node. In your example, $xml holds the root node <info/>. Here's a great tip: always name the variable that holds your XML document after its root node, it will prevent such confusion.

    Also, as Ward Muylaert pointed out, you need to save the file.

    Here's the corrected example:

    // load the document
    // the root node is <info/> so we load it into $info
    $info = simplexml_load_file('test.xml');
    
    // update
    $info->user->name->nameCoordinate->xName = $xPostName;
    $info->user->name->nameCoordinate->yName = $yPostName;
    
    // save the updated document
    $info->asXML('test.xml');
    
    0 讨论(0)
  • 2020-11-29 09:18

    You have to write the changes back to the file, use the asXML method of the SimpleXMLElement.

    0 讨论(0)
  • 2020-11-29 09:23

    try like this.

    $xmlDoc = new \DOMDocument;
    $xmlDoc->load('Books.xml');
    $response = $xmlDoc->getElementsByTagName('Text');
    
    foreach ($response as $node){
            $node->nodeValue = 'test';
        }
    $xmlDoc->saveXML();
    
    

    this might not the best answer but it worked for me.

    0 讨论(0)
提交回复
热议问题