PHP SimpleXML + Get Attribute

2019-01-09 08:56发布

The XML I am reading looks like this:

<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>

To get (for example) The number of the latest episode, I would do:

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

This works just fine. But what would I do to get the ID from <show id="8511"> ?

I have tried something like:

$id = $xml->show;
$id = $xml->show[0];

But none worked.

Update

My code snippet:

$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

7条回答
爷的心禁止访问
2楼-- · 2019-01-09 09:33

You need to format your XML properly and let it have examply using <root></root> or <document></document> anything .. see XML specification and examples at 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);
查看更多
霸刀☆藐视天下
3楼-- · 2019-01-09 09:35

This should work.

$id = $xml["id"];

Your XML root becomes the root of the SimpleXML object; your code is calling a chid root by the name of 'show', which doesn't exist.

You can also use this link for some tutorials: http://php.net/manual/en/simplexml.examples-basic.php

查看更多
叛逆
4楼-- · 2019-01-09 09:39

This should work. You need to use attributes with type (if sting value use (string))

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

Or this:

$id = strip_tags($xml->show->attributes()->id);
var_dump($id);
查看更多
别忘想泡老子
5楼-- · 2019-01-09 09:43

try this

$id = (int)$xml->show->attributes()->id;
查看更多
霸刀☆藐视天下
6楼-- · 2019-01-09 09:45

You need to use attributes

I believe this should work

$id = $xml->show->attributes()->id;
查看更多
地球回转人心会变
7楼-- · 2019-01-09 09:52

After you have correctly load the xml file using the SimpleXML objecto you can do a print_r($xml_variable) and you can easily find which attributes you can access. As other users said $xml['id'] also worked for me.

查看更多
登录 后发表回答