简体   繁体   中英

Parsing XML from URL using SimpleXML

I'm trying to echo the XML content at this URL but I'm having difficulty. Here's what I have so far:

$url = "GetVideosServlet?queryId=1";

$xml = simplexml_load_file($url);

$value = (string) $xml->results->item[0]->id;

echo $value;

I keep getting the error that I'm trying to get the property of a non-object. But I was under the impression simplexml_load_file converts my XML string INTO an object??

If anyone could show me how to echo out any of the content, I'd be very grateful.

I think you just miss a tag which is query , try:

$value = (string) $xml->query->results->item[0]->id;
echo $value;

When you are debugging print_r and var_dump are very handy! for example in this case if you dumped the $xml right after loading it you would have noticed that you missed out the SimpleXMLElement Object query.

$url = "http://176.34.224.80/REMPADRecSys/GetVideosServlet?queryId=1";
$xml = simplexml_load_file($url);
echo "<pre>";
print_r($xml);

Would give you the output:

SimpleXMLElement Object
(
    [query] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 1
                )

            [results] => SimpleXMLElement Object
                (
                    [item] => Array
                        (
                            [0] => SimpleXMLElement Object
                                (
                                    [id] => GZ7w39jpqwo
                                    [rank] => 1
                                    [explanation] => Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla a massa lectus, sed convallis sapien. Curabitur sem mauris, ullamcorper ut. 
                                )

and so the correct reference would have been $xml->query->results->item[0]->id; like @Lake mentioned. Happy debugging.

simplexml_load_file(rawurlencode('http://176.34.224.80/REMPADRecSys/GetVideosServlet?queryId=1'));

尝试这个。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM