user10274338
user10274338

Reputation:

Add node to a XML variable and Save it

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);

Upvotes: 0

Views: 387

Answers (2)

balakrishnan
balakrishnan

Reputation: 383

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.

Upvotes: 0

ThW
ThW

Reputation: 19492

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>

Upvotes: 1

Related Questions