douhuan1257 2013-07-17 00:45
浏览 34
已采纳

使用SimpleXml访问PHP的第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>

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;

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!

  • 写回答

1条回答 默认 最新

  • duanjiu1003 2013-07-17 00:58
    关注

    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;
    

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址