检查字符串是否是xml中的属性

时间:2014-05-02 22:00:31

标签: php xml

我正在尝试了解SimpleXMLElement(不是DOM),这是我第一次处理XML和PHP。我想查看是否string == node[attribute];那么,如果another string == node/child[attribute];最后,如果last string == node/child/grandchild[attribute='att']

使用my xml文件中的单词,伪代码为:

if dish[name] == "Potato":
  if how[name] == "fried":
    if price[size=small] == "1.23":
      do something.

XML文件:

<menu>
  <dish name="Potato">
    <how name="fried">
      <price size="small">1.23</price>
      <price size="big">4.56</price>
    </how>
    <how name="baked">
      <price size="small">5.23</price>
      <price size="big">6.56</price>
    </how>
  </dish>
</menu>

PHP

$xml = simplexml_load_file('xmlfile.xml');


if ( (string) $xml->dish['name'] == "Potato" ) {
  if ( (string) $xml->dish->how['name'] == 'fried' ) {
    if ( (string) $xml->dish->how['name="fried"']->price['size="small"'] == '1.23' ) {
      echo 'OK';      
    }
  } 
} else { 
    echo 'something is wrong';
}

唯一有效的是我可以检查'Potato'是否是一道菜[“name”]。其他一切都是错的,我无法弄清楚如何去做。

谢谢,

1 个答案:

答案 0 :(得分:0)

要选择小炸土豆的价格,您可以使用xpath,就像SQL for XML:

$xml = simplexml_load_string($x); // assume XML in $x

$price = $xml->xpath("/menu/dish[@name = 'Potato']/how[@name = 'fried']/price[@size = 'small']")[0];

现在,如果有小炸土豆,$price = 1.23,还有NULL

if (! is_null($price)) 
    echo "you can get it for $price!";
else
    echo "it is not available, sorry!";

请注意,xpath - 行...[0];末尾的数组解除引用需要PHP >= 5.4。如果您使用的是较低版本,请更新或执行:

$price = $xml->xpath("/menu/dish[@name = 'Potato']/how[@name = 'fried']/price[@size = 'small']");
$price = $price[0];

在行动中看到它:https://eval.in/145721

相关问题