将节点添加到XML变量并保存

时间:2018-08-29 13:48:08

标签: php xml xml-parsing simplexml

我想在保存XML变量之前将XML节点即<name>B07BZFZV8D</name>添加到XML变量。
我想在“ Self”元素中添加“ name”节点。

#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 个答案:

答案 0 :(得分:1)

使用DOM,您可以使用文档对象的方法来创建节点,并使用父节点的方法来将其插入/添加到层次结构中。

DOMDocument具有create*方法,用于不同的节点类型(元素,文本,cdata节,注释等)。父节点(元素,文档,片段)具有appendChildinsertBefore之类的方法来添加/删除它们。

Xpath可用于从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();

输出:

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

答案 1 :(得分:0)

使用@ThW代码: 需要更改“创建元素”功能

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

它适用于php7.0。检查它是否适合您。