gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:06:21 24 4
gpt4 key购买 nike

我想在 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 - 在 xpath 查询中使用 php 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14635654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com