0

我正在尝试使用 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>
4

2 回答 2

2

这是一个基于SimpleXML的快速解决方案:

$gold = new SimpleXMLElement($xml);

foreach ($gold->coin as $coin) {
    $coin->price = str_replace('500', $rest, (string) $coin->price);
}

echo $gold->asXML();

工作演示

于 2013-07-26T09:08:31.480 回答
0

哦,嘿,这是我的错误,该功能完美无缺,而不是

     if('500' == $eventN)

正确的是

     if('500 rupees' == $eventN)

哑的

于 2013-07-26T09:12:46.210 回答