Search code examples
phparraysobjectrsssimplexml

Accessing multi-dimensional array object created with simplexml_load_file in PHP returns null?


I have a RSS object $rssObject created using the PHP simplexml_load_file function, the goal is to get the value of [href].

var_dump($rssObject) returns the following:

Array
(
    [0] => SimpleXMLElement Object
        (
            [link] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [href] => https://www.example.com
                                )

                        )

I have tried unsuccessfully to get the contents of [href] using this notation which returns null

$rssObject[0]->link[0]->{'@attributes'}['href'];

Why is this?


Solution

  • In SimpleXML, attributes are accessed using array notation:

    $xml = simplexml_load_file();
    $url = $xml[0]->link[0]['href'];
    

    See "Example #5 Using attributes" in the PHP manual.