PHP SimpleXML + 获取属性

标签 php xml simplexml

我正在阅读的 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);

奥利。 XML:

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

最佳答案

这应该可行。

$id = $xml["id"];

您的 XML 根成为 SimpleXML 对象的根;您的代码正在调用名为“show”的 chid 根,但该名称不存在。

您也可以使用此链接获取一些教程:http://php.net/manual/en/simplexml.examples-basic.php

关于PHP SimpleXML + 获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10537657/

相关文章:

php - html5获取文件路径

java - Jaxb 编码预期为 xsi :nil ="true" in the element when the value is decimal which will be null,,但 xsi:nil ="true"未出现

php - 如何从 MYSQL 数据库导出 XML 文件为每条记录创建一个 XML 文件?

php - 使用XPath获取节点名称

php - 在 PHP 中处理大型 XML 的最佳方式

php - 无法从 PHP 打开文件

javascript - 使用 PHP 从数据库检索值、存储在输入文本和文本区域中、更改、将新值传递给数据库?

php - 删除除我想要的所有数组元素吗?

xml - 使用 Groovy (gpath) 获取 XML 属性的值

php - 从 XMLReader 打开的 simplexml 中的 CData