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条)

报告相同问题?

悬赏问题

  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题