在xpath查询中使用php变量 - php

我想在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 ) ) )

我可能错过了一些非常简单的东西,但被卡住了!

参考方案

您应该在变量周围添加单引号

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

PHP-复选框组 - php

我有一个需要发布的表单复选框组。<input type="checkbox" value="true" checked name="chk0[]"> <input type="checkbox" value="false" name=…

php Singleton类实例将在多个会话中保留吗? - php

举一个简单的例子,如果我想计算一个不使用磁盘存储的脚本的命中次数,我可以使用静态类成员来执行此操作吗?用户1:<?php $test = Example::singleton(); $test->visits++; ?> 用户2:<?php $test = Example::singleton(); $test->visits+…

当使用jquery的id做某事时,id可以来自任何一种标记吗? - php

我是JQuery的新手,我正尝试使用PHP,HTML和JQuery编写代码。我想用具有ID的标签替换HTML中的所有<?php echo $var; ?>。例如,我想使用<div id="name"></div>之类的东西,然后使用$("#name")将其显示在该div字段中。我的问…

PHP中奇怪的sprintf行为 - php

我试图做sprintf("<%s>", "Sat");,但是什么也没出现。当您删除小于符号时,它将再次开始工作。任何人都经历过这种行为以及是否会发生这种情况?因为我认为这是一个错误。您甚至可以在这里使用printf .....获得相同的结果。http://writecodeonline.com/php/ 参…

jQuery不起作用 - php

我正在使用带有ajax的jquery。有时,给出错误$未定义。这是我的代码:<script language="javascript" type="text/javascript"> var base_path="<? echo $this->baseUrl().'/…