我正在尝试使用 PHP 编辑 XML 文档,但它似乎不起作用,想知道我哪里出错了!
我正在尝试按照我在网上找到的以下方式进行操作。谁能告诉我正确的方向?
XML
<gold>
<coin>
<id>1</id>
<title>Gold Coin 50 Grams</title>
<price>500 rupees</price>
<dimension>20 MM</dimension>
<thumb_url>http://animsinc.com/Expertise-media.png</thumb_url>
</coin>
<coin>
<id>2</id>
<title>Gold Coin 50 Grams</title>
<price>500 rupees</price>
<dimension>20 MM</dimension>
<thumb_url>
http://animsinc.com/Expertise-media.png</thumb_url>
</coin>
...
</gold>
PHP 代码
$xmlDoc = new DOMDocument();
$xmlDoc->loadXml($str);
$events = $xmlDoc->getElementsByTagName("coin");
foreach($events as $event){
$eventNames = $event->getElementsByTagName("price");
$eventN = $eventNames->item(0)->nodeValue;
if('500' == $eventN){ // ** Failed here, instead of '500',
// I used '500 rupees' and it worked, as that matches the original text.**
$eventNames->item(0)->nodeValue = $rest ;
}
}
var_dump($xmlDoc->saveXML());
这是期望的结果。请注意我如何将价格标签更改为 2495 卢比。
<gold>
<coin>
<id>1</id>
<title>Gold Coin 50 Grams</title>
<price>2495 rupees</price>
<dimension>20 MM</dimension>
<thumb_url>http://animsinc.com/Expertise-media.png</thumb_url>
</coin>
<coin>
<id>2</id>
<title>Gold Coin 50 Grams</title>
<price>2495 rupees</price>
<dimension>20 MM</dimension>
<thumb_url>
http://animsinc.com/Expertise-media.png</thumb_url>
</coin>
...
</gold>