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

问题描述 投票:0回答:2

我想在保存之前将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);
php xml xml-parsing simplexml
2个回答
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>

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。检查它是否适合您。

© www.soinside.com 2019 - 2024. All rights reserved.