通过父属性访问值

发布于 2024-09-03 20:11:06 字数 661 浏览 1 评论 0原文

我希望根据传递的属性通过 xpath 获取值 A-1。

我已经通过 php 从上一页传递了单元的索引属性,并通过全局 GET 访问它:

$value = intval($_GET['index']);

xml:

<UNIT index='1'>
     <ID>A-1</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>
<UNIT index='2'>
     <ID>A-2</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>

我试图使用以下命令回显它:

$xml = new SimpleXMLElement('demo.xml',NULL,true);

echo $xml->UNIT[$value]->ID;

我知道我正在获取我需要传递的“1”因为我回显了 $value 来检查,但是 它给了我 A-2 的 ID,这将是 xml 索引号(从 0 开始)——而不是我的属性索引号。

I am looking to get the value A-1 through xpath based on a passed attribue.

I have passed the index attribute of the unit through php from a previous page and am accessing it by global GET:

$value = intval($_GET['index']);

the xml:

<UNIT index='1'>
     <ID>A-1</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>
<UNIT index='2'>
     <ID>A-2</ID>
     <MANUFACTURER>testing inc.</MANUFACTURER>
</UNIT>

I'm trying to echo it out using:

$xml = new SimpleXMLElement('demo.xml',NULL,true);

echo $xml->UNIT[$value]->ID;

I know i'm getting the "1" that I need passed through because I echo'd $value to check, but
its giving me the ID of A-2, which would be the xml index number (starting from 0) - not my attribute index number.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

青衫儰鉨ミ守葔 2024-09-10 20:11:06

您可以使用 SimpleXMLElement::xpath 方法来查询特定的 < code>UNIT 您想要使用 XPath 查询(如 //UNIT[@index=2])。

$value = intval($_GET['index']);
$xml   = new SimpleXMLElement('demo.xml',NULL,true);
$units = $xml->xpath("//UNIT[@index=$value]"); // xpath returns an array
if (isset($units[0])) {
    echo $units[0]->ID;
} else {
    echo "No unit with index $value";
}

You can use the SimpleXMLElement::xpath method to query for the specific UNIT that you want with an XPath query like //UNIT[@index=2].

$value = intval($_GET['index']);
$xml   = new SimpleXMLElement('demo.xml',NULL,true);
$units = $xml->xpath("//UNIT[@index=$value]"); // xpath returns an array
if (isset($units[0])) {
    echo $units[0]->ID;
} else {
    echo "No unit with index $value";
}
旧竹 2024-09-10 20:11:06

使用

//UNIT[@index=$value]/ID

Use:

//UNIT[@index=$value]/ID

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文