0

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

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

hello sir thanks for your reply, this is not workiing for me i am getting the same result with no name added...i have given the proper xml file can you please have a look
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.