【问题标题】:Add node to a XML variable and Save it将节点添加到 XML 变量并保存
【发布时间】:2018-08-29 13:48:07
【问题描述】:

我想在保存之前将 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


    【解决方案1】:

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

    DOMDocument 具有用于不同节点类型(元素、文本、cdata 部分、注释...)的create* 方法。父节点(元素、文档、片段)具有像 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>
    

    【讨论】:

    • 您好,先生,谢谢您的回复,这对我不起作用,我得到了相同的结果,但没有添加名称...我已经给出了正确的 xml 文件,您可以看看
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2018-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-04
      相关资源
      最近更新 更多