使用Xpath& amp;查找基于属性的XML节点然后更新它的孩子的价值

时间:2012-01-07 23:04:10

标签: php xml

实现这一目标的最佳/最有效方式? DOM文档? Xpath的?两者的混合?

<currencies>
  <currency id="USD">
    <title>United States Dollar</title>
    <loc>American Samoa, British Indian Ocean Territory, Caribbean Netherlands, Ecuador, El Salvador, Guam, Haiti, Marshall Islands, Micronesia, Northern Mariana Islands, Palau, Panama, Puerto Rico, Timor-Leste, Turks and Caicos Islands, United States, U.S. Virgin Islands, Barbados (as well as Barbados Dollar), Bermuda (as well as Bermudian Dollar), Zimbabwe</loc>
    <rate>1.2723</rate>
    <timestamp>1325962378</timestamp>
  </currency>
</currencies>

我需要根据我所做的属性'id'来访问货币节点:

$xml->xpath('//currency[id="'.$currId.'"]');

如何在保存文件之前访问名为“rate”的子节点并编辑其值?

1 个答案:

答案 0 :(得分:1)

你的XPath几乎是正确的;你只是错过了一个@符号。这是一个适用于SimpleXML的解决方案:

$nodes = $xml->xpath('//currency[@id="'.$currId.'"]'); // returns an array
$nodes[0]->rate = $new_rate; // set the first element's rate to the rate stored
                             // in $new_rate
$xml->asXML($filename);  // save the XML to the file $filename