Add node to a XML variable and Save it

二次信任 提交于 2019-12-13 03:14:53

问题


i want to add the xml node i.e <name>B07BZFZV8D</name> to the XML variable before saving it.
I want to add the 'name' node inside the 'Self' Element.

#Previously i use to save it directly like this, 

$Response        #this is the respnse from api

$dom = new DOMDocument;
$dom->preserveWhiteSpace = FALSE;
$dom->loadXML($Response);


##saving in file
$myfile = file_put_contents('data.xml', $Response.PHP_EOL , FILE_APPEND | LOCK_EX);

回答1:


With DOM you use methods of the document object to create the node and methods of the parent node to insert/add it to the hierarchy.

DOMDocument has create* methods for the different node types (element, text, cdata section, comment, ...). The parent nodes (element, document, fragment) have methods like appendChild and insertBefore to add/remove them.

Xpath can be used to fetch nodes from the DOM.

$document = new DOMDocument;
$document->preserveWhiteSpace = FALSE;
$document->loadXML($xmlString);
$xpath = new DOMXpath($document);

// fetch the first Data element inside the Report document element
foreach ($xpath->evaluate('/Report/Data[1]') as $data) {
    // create the name element and append it
    $name = $data->appendChild($document->createElement('name'));
    // create a node for the text content and append it
    $name->appendChild($document->createTextNode('Vivian'));
}

$document->formatOutput = TRUE;
echo $document->saveXML();

Output:

<?xml version="1.0" encoding="UTF-8"?>
<Report>
  <Data>
    <id>87236</id>
    <purchase>3</purchase>
    <address>XXXXXXXX</address>
    <name>Vivian</name>
  </Data> 
</Report>



回答2:


Using @ThW Code: Need to change Create Element functionality

$document = new DOMDocument;
$document->preserveWhiteSpace = FALSE;
$document->loadXML($xmlString);
$xpath = new DOMXpath($document);
// fetch the first Data element inside the Report document element
foreach ($xpath->evaluate('/Report/Data[1]') as $data) {
// create the name element with value and append it
$xmlElement = $document->createElement('name', 'Vivian');
$data->appendChild($xmlElement);
}
$document->formatOutput = TRUE;
echo $document->saveXML();

It works for me with php7.0. Check it works for you.



来源:https://stackoverflow.com/questions/52079003/add-node-to-a-xml-variable-and-save-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!