尝试使用PHP中的动态变量编辑XML文档

时间:2013-07-26 07:38:36

标签: php xml

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

2 个答案:

答案 0 :(得分:2)

以下是基于SimpleXML的快速解决方案:

$gold = new SimpleXMLElement($xml);

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

echo $gold->asXML();

Working demo

答案 1 :(得分:0)

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

     if('500' == $eventN)

正确的人

     if('500 rupees' == $eventN)