PHP SimpleXML + 获取属性

19
我正在阅读的XML长这样:

<show id="8511">

    <name>The Big Bang Theory</name>
    <link>http://www.tvrage.com/The_Big_Bang_Theory</link>
    <started>2007-09-24</started>
    <country>USA</country>

    <latestepisode>
        <number>05x23</number>
        <title>The Launch Acceleration</title>
    </latestepisode>

</show>

要获取(例如)最新一集的编号,我会这样做:

$ep = $xml->latestepisode[0]->number;
这个做得很好。但如何从<show id="8511">中获取ID呢?
我尝试过类似这样的代码:
$id = $xml->show;
$id = $xml->show[0];

但是没有一个有效。

更新

我的代码片段:

$url    = "http://services.tvrage.com/feeds/episodeinfo.php?show=".$showName;
$result = file_get_contents($url);
$xml = new SimpleXMLElement($result);

//still doesnt work
$id = $xml->show->attributes()->id;

$ep = $xml->latestepisode[0]->number;

echo ($id);

Ori. XML:

http://services.tvrage.com/feeds/episodeinfo.php?show=The.Big.Bang.Theory

http://php.net/simplexml.examples-basic - hakre
可能是重复的问题:从SimpleXML访问@attribute - 供参考。 - hakre
请查看以下链接: https://dev59.com/-mkv5IYBdhLWcg3wghIi#19289857 - Mudassar Ali Sahil
7个回答

33
这应该可以工作。
$id = $xml["id"];

你的XML根节点成为SimpleXML对象的根节点;你的代码正在调用一个名为“show”的子根节点,但该节点不存在。

你还可以使用这个链接来进行一些教程:http://php.net/manual/en/simplexml.examples-basic.php


2
这似乎解决了问题!非常感谢!(下次我应该花更多时间查看示例:() - r0skar

12

您需要使用属性

我相信这应该可以工作

$id = $xml->show->attributes()->id;

这不会起作用... show 是默认根 ... 他需要正确地包装 xml - Baba
很不幸,我一直收到“警告:main() [function.main]:节点在...中不再存在”的提示。 - r0skar

9

这应该是可行的。 您需要使用带有 type 属性的内容(如果是字符串值,请使用 (string))。

$id = (string) $xml->show->attributes()->id;
var_dump($id);

或者是这样的:
$id = strip_tags($xml->show->attributes()->id);
var_dump($id);

7
您需要使用 attributes() 方法来获取属性。
$id = $xml->show->attributes()->id;

您也可以这样做:
$attr = $xml->show->attributes();
$id = $attr['id'];

或者你可以尝试这样做:
$id = $xml->show['id'];

看着你问题的编辑(<show>是你的根元素),尝试这样做:

$id = $xml->attributes()->id;

或者

$attr = $xml->attributes();
$id = $attr['id'];

或者

$id = $xml['id'];

第一个和第二个示例不幸地输出了“警告:main() [function.main]:节点在...中不再存在”,而最后一个示例则根本没有显示任何内容。 - r0skar
可以了,如果你也修改了@Sam的答案,请告诉我,因为那样的话我会更改正确的答案并选择你的答案。 - r0skar
@Andrej:不,Sam的答案一开始就是那样的 :-P 我只是编辑了格式。 - gen_Eric

3

试一下

$id = (int)$xml->show->attributes()->id;

0

在正确使用SimpleXML对象加载xml文件后,您可以执行print_r($xml_variable),并且可以轻松找到可以访问哪些属性。像其他用户所说的那样,$xml ['id'] 对我也奏效。


0
你需要正确格式化你的 XML,并且让它包含例如 <root></root> 或者 <document></document> 之类的东西。请查看 XML 规范和示例,链接在 http://php.net/manual/en/function.simplexml-load-string.php
$xml = '<?xml version="1.0" ?> 
<root>
<show id="8511">
    <name>The Big Bang Theory</name>
    <link>http://www.tvrage.com/The_Big_Bang_Theory</link>
    <started>2007-09-24</started>
    <country>USA</country>

    <latestepisode>
        <number>05x23</number>
        <title>The Launch Acceleration</title>
    </latestepisode>

</show>
</root>';

$xml = simplexml_load_string ( $xml );
var_dump ($xml->show->attributes ()->id);

很遗憾,我无法控制XML的格式! - r0skar
我在我的帖子中添加了原始的XML源代码! - r0skar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接