PHP SimpleXML +获取属性

r0s*_*kar 18 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>
Run Code Online (Sandbox Code Playgroud)

要获得(例如)最新一集的数量,我会这样做:

$ep = $xml->latestepisode[0]->number;
Run Code Online (Sandbox Code Playgroud)

这很好用.但是如何从中获取ID <show id="8511">呢?

我尝试过类似的东西:

$id = $xml->show;
$id = $xml->show[0];
Run Code Online (Sandbox Code Playgroud)

但都没有效果.

更新

我的代码片段:

$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);
Run Code Online (Sandbox Code Playgroud)

大利.XML:

http://services.tvrage.com/feeds/episodeinfo.php?show=The.Big.Bang.Theory
Run Code Online (Sandbox Code Playgroud)

Kne*_*ZOD 31

这应该工作.

$id = $xml["id"];
Run Code Online (Sandbox Code Playgroud)

您的XML根目录成为SimpleXML对象的根; 你的代码通过'show'的名称调用chid root,这个名称不存在.

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

  • 这似乎可以解决问题!非常感谢!(我应该花更多的时间来看下一次的例子:() (2认同)

Raw*_*ode 12

您需要使用属性

我相信这应该有效

$id = $xml->show->attributes()->id;
Run Code Online (Sandbox Code Playgroud)


小智 9

这应该工作.您需要使用带有类型的属性(如果使用sting值(字符串))

$id = (string) $xml->show->attributes()->id;
var_dump($id);
Run Code Online (Sandbox Code Playgroud)

或这个:

$id = strip_tags($xml->show->attributes()->id);
var_dump($id);
Run Code Online (Sandbox Code Playgroud)


Roc*_*mat 7

您需要使用attributes()获取属性.

$id = $xml->show->attributes()->id;
Run Code Online (Sandbox Code Playgroud)

你也可以这样做:

$attr = $xml->show->attributes();
$id = $attr['id'];
Run Code Online (Sandbox Code Playgroud)

或者你可以尝试这个:

$id = $xml->show['id'];
Run Code Online (Sandbox Code Playgroud)

查看问题的编辑(<show>是您的根元素),试试这个:

$id = $xml->attributes()->id;
Run Code Online (Sandbox Code Playgroud)

要么

$attr = $xml->attributes();
$id = $attr['id'];
Run Code Online (Sandbox Code Playgroud)

要么

$id = $xml['id'];
Run Code Online (Sandbox Code Playgroud)