2013-01-31 93 views
2

我想在xpath語句中使用php變量。有一個類似的線程here其答案不能解決我的問題。在xpath查詢中使用php變量

下面是示例代碼(均未$ 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))) 

我可能缺少一些事情很簡單,但我堅持!

回答

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

去過,因爲我已經使用XPath語法一段時間,但是,按扣,它看起來像只diferrences的單引號:

以下是現在等效。

$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']");