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

使用SimpleXml访问PHP的第n个XML元素

I have an xml formatted like this:

  1. <?xml version="1.0"?>
  2. <root>
  3. <foo id="1">
  4. <bar>text</bar>
  5. </foo>
  6. <foo id="2">
  7. <bar>text2</bar>
  8. </foo>
  9. </root>

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

  1. $xml = simplexml_load_file('file.xml');
  2. 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-16 16: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.)

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

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

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部