使用 SimpleXml 在 PHP 中访问 XML 的第 n 个元素 [英] Accessing nth element of XML in PHP with SimpleXml

查看:24
本文介绍了使用 SimpleXml 在 PHP 中访问 XML 的第 n 个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个格式如下的 xml:

I have an xml formatted like this:

<?xml version="1.0"?>
<root>
  <foo id="1">
    <bar>text</bar>
  </foo>
  <foo id="2">
    <bar>text2</bar>
  </foo>
</root>

我知道,在 PHP 中,您可以像这样访问使用 SimpleXML 加载的 xml 文件的第 n 个元素:

I know that, in PHP, you I can access the nth element of an xml file loaded with SimpleXML like so:

$xml = simplexml_load_file('file.xml');
echo $xml->foo[2]->bar;

但我需要通过从 $_GET 中提取的变量来访问元素,所以:

but I need to access an element by a variable pulled from $_GET, so:

echo $xml->foo[$var]->bar;

这似乎不起作用,我真的很感激任何建议.谢谢!

This doesn't seem to work, and I'd really appreciate any advice. Thanks!

推荐答案

SimpleXML 似乎以与普通 PHP 数组略有不同的方式区分数字和非数字数组偏移量,因此您需要将变量强制转换为整数第一的.(查询字符串的所有输入都是一个字符串,直到您告诉 PHP 否则.)

It seems SimpleXML distinguishes between numeric and non-numeric array offsets in a slightly different way to a normal PHP array, so you need to cast your variable to an integer first. (All input from the query string is a string until you tell PHP otherwise.)

$var = intval($_GET['var']);
echo $xml->foo[$var]->bar;

这会将字符串 '1' 转换为整数 1,并给出您需要的结果.

This will turn the string '1' into the integer 1, and should give the result you require.

这篇关于使用 SimpleXml 在 PHP 中访问 XML 的第 n 个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆