简体   繁体   English

修改现有 XML 文档中的节点值并使用 DOM PHP 打印结果

[英]Amend node value in existing XML document and print result with DOM PHP

I am looking for the best method to replace a node value using DOM in PHP.我正在寻找在 PHP 中使用 DOM 替换节点值的最佳方法。

An example XML would be, which is stored as data.xml :一个示例 XML 将是,它存储为data.xml

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

I have been following https://www.w3schools.com/php/php_xml_dom.asp , which works great to print out the XML file without any edits using the following code:我一直在关注https://www.w3schools.com/php/php_xml_dom.asp ,它可以很好地打印出 XML 文件,无需使用以下代码进行任何编辑:

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load("data.xml");


print $xmlDoc->saveXML();
?>

Now I'm not sure how to go about editing the values of, for example, change Jani to Smith and print the new changed xmlDoc.现在我不确定如何编辑 go 的值,例如将Jani更改为Smith并打印新更改的 xmlDoc。

Try:尝试:

$xpath = new DOMXPath($xmlDoc);
$from = $xpath->query('/note//from')[0];
$from->nodeValue="John";
echo $xmlDoc->saveXML();

Output: Output:

<?xml version="1.0" encoding="UTF-8"?>
<note>
<to>Tove</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM