dougong8012 2013-07-26 07:38
浏览 54
已采纳

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

I am trying to edit an XML document using PHP, but it does not seem to work, wonder where I am going wrong!

I am trying to do it the following way which I found online. Can anyone please show me the right direction?

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 Code

$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());

Here's the desired result. Notice how I've changed the price tag to 2495 rupees.

 <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条回答 默认 最新

  • doumi4676 2013-07-26 09:08
    关注

    Here's a quick solution based on 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条)

报告相同问题?