我正在阅读的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
你需要使用属性
我相信这应该有效
$id = $xml->show->attributes()->id;
这应该有效。您需要使用带有类型的属性(如果刺痛值使用(字符串))
$id = (string) $xml->show->attributes()->id;
var_dump($id);
或者这个:
$id = strip_tags($xml->show->attributes()->id);
var_dump($id);
您需要使用 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'];
试试这个
$id = (int)$xml->show->attributes()->id;
正确格式化你的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);
使用 SimpleXML 对象正确加载 xml 文件后,您可以执行print_r($xml_variable)
,并且可以轻松找到可以访问的属性。 正如其他用户所说$xml['id']
也为我工作。