0

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?

2
  • Why has this been down-voted? Please see answer, it justified this question when the var_dump is outputting a misleading output! Commented Jul 14, 2017 at 10:01
  • 1
    Yeah, this is a very common confusion, and we should really have a canonical answer explaining it. Commented Jul 14, 2017 at 11:36

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi can you explain why I don't have to use [@attributes] as a key?
The var_dump representation you see is .. a lie. SimpleXML does some magic, and you have to adhere to its rules.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.