Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/242.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Xpath:在Xpath字符串中使用变量_Php_Xml_Xpath - Fatal编程技术网

Php Xpath:在Xpath字符串中使用变量

Php Xpath:在Xpath字符串中使用变量,php,xml,xpath,Php,Xml,Xpath,我是Xpath新手,如果这是一个愚蠢的问题,我很抱歉,但这让我发疯。我有一个如下所示的xml文件: <ItemList> <Item ID="01"> <Color>Red</Color> <Type>Box</Type> <Material>Metal</Material> </Item> <Item ID="02"> <Color>

我是Xpath新手,如果这是一个愚蠢的问题,我很抱歉,但这让我发疯。我有一个如下所示的xml文件:

<ItemList>
<Item ID="01">
    <Color>Red</Color>
    <Type>Box</Type>
    <Material>Metal</Material>
</Item>
<Item ID="02">
    <Color>Blue</Color>
    <Type>Cone</Type>
    <Material>Wood</Material>
</Item> 
</ItemList>

据我所知,我试图插入变量的地方的语法是错误的。我也尝试了“+$id+”,但得到了相同的错误。任何帮助都将不胜感激。

在本测试中效果良好……嗯。知道我为什么会犯那个错误吗?如果我用它工作的数字替换变量?我错过了什么?哦!没关系,我的错。url中的参数是“2”而不是“02”。但是感谢您的帮助,您可以通过使用evaluate$xpath->evaluatestring//ItemList/Item[@ID='02']/Color;避免类似错误;。这将以字符串形式返回列表中的第一个节点,如果未找到节点,则返回空字符串。
$id = $_GET['code'];

$doc = new DomDocument;
$doc->validateOnParse = true;
$doc->Load('file.xml');

$xpath = new DOMXpath($doc);

$Color = $xpath->query("//ItemList/Item[@ID='" . $id . "']/Color");

echo $Color->item(0)->nodeValue;