我想在xpath语句中使用php变量。有一个类似的帖子here,其答案无法解决我的问题。
这是示例代码($ r1或$ r2都没有创建预期的数组)
<?php
$xml = simplexml_load_file("menu.xml");
$term = "one";
$r1 = $xml->xpath("//category[@name=$term]");
$r2 = $xml->xpath("//category[@name=" . $term . "]");
$r3 = $xml->xpath("//category[@name='one']");
echo ('$r1 = '); print_r($r1);
echo ('<br>$r2 = '); print_r($r2);
echo ('<br>$r3 = '); print_r($r3);
?>
XML
<?xml version="1.0" encoding="ISO-8859-1"?>
<menu>
<category name="one">
<item>Tomato and Cheese</item>
<item>Onions</item>
<item>Broccoli</item>
</category>
<category name="two">
<item>Burger and Fries</item>
<item>Chicken Sandwich</item>
</category>
<category name="three">
<item>Filet of Fish</item>
<item>Exotic Meat Stew</item>
</category>
输出
$r1 = Array ( )
$r2 = Array ( )
$r3 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
我可能错过了一些非常简单但却陷入困境的事情!
答案 0 :(得分:3)
您应该在变量
周围添加单引号$xml = simplexml_load_string($xml);
$term = "one";
$r1 = $xml->xpath("//category[@name='$term']");
$r2 = $xml->xpath("//category[@name='" . $term . "']");
$r3 = $xml->xpath("//category[@name='one']");
echo ('$r1 = '); print_r($r1);
echo ('<br>$r2 = '); print_r($r2);
echo ('<br>$r3 = '); print_r($r3);
输出
$r1 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
$r2 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
$r3 = Array ( [0] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => one ) [item] => Array ( [0] => Tomato and Cheese [1] => Onions [2] => Broccoli ) ) )
答案 1 :(得分:1)
因为我使用了xpath语法已经有一段时间了,但是,通过演绎,它看起来像是单引号的唯一不同之处:
以下是现在等效。
$xml = simplexml_load_file("menu.xml");
$term = "one";
$r1 = $xml->xpath("//category[@name='$term']");
$r2 = $xml->xpath("//category[@name='" . $term . "']");
$r3 = $xml->xpath("//category[@name='one']");