SimpleXMLElement array

Good day,

This is the output of a var_dump. I would like to know if someone has an idea on how I can get the value
contain in the attribues contained in $self ? thanks.

Code:

$self = $xml->xpath(‘/rss/channel/atom:link[@rel=\‘self\’]’);
var_dump($self);

Output:

array
0 =>
object(SimpleXMLElement)[2]
public ‘@attributes’ =>
array
‘rel’ => string ‘self’ (length=4)
‘type’ => string ‘application/rss+xml’ (length=19)
‘href’ => string ‘http://beta.geogratis.gc.ca/api/en/nrcan-rncan/ess-sst/?max-results=50&entry-
type=full&q=chambly&locale=en_CA&alt=rss’ (length=117)

Welcome to the SP forums.

http://www.php.net/manual/en/simplexml.examples-basic.php
Look at example #4.

Something like:


foreach ($self->attributes as $key=>$value) {
   echo $key . ' - ' . $value . PHP_EOL;
}

Thanks for replying Guido2004.

The proposed solution cause an error: Notice: Trying to get property of non-object in

any idea ? thanks.

Ok, so $self is not an object. Looking at your var_dump, you’ll see that it’s an array, and the object is the first element of that array. So try


foreach ($self[0]->attributes as $key=>$value) {
   echo $key . ' - ' . $value . PHP_EOL;
}  

That is a special one, I guest. the proposed code makes sense, but does not return anything.

How can something be there, but and not accessible? Thanks.

foreach ($self[0]->attributes as $key=>$value) {
echo $key . ’ - ’ . $value . PHP_EOL;
}

The @ in ‘@attributes’ is strange. I tried to put a @ in an xml file and load it with SimpleXML, but it gives me an error.

Can you post the content of the original file here?

Never mind, I browsed around in the manual a bit, and I guess it’s got to do with xpath.
But I don’t know if you can do something like this:


foreach ($self[0]->@attributes as $key=>$value) {
   echo $key . ' - ' . $value . PHP_EOL;
}  

Try this:

$self = $xml->xpath('/rss/channel/atom:link[@rel=\\'self\\']');
$attributes = $self[0]->attributes();
var_dump($attributes);

That should print out the simplexml object containing the attributes.
If you want to access and get the value for a specific attribute, try this.

$attribute_value = (string) $self[0]->attributes()->href;

Yes, finally found it myself, attributes() with the (): http://php.net/manual/en/simplexmlelement.attributes.php


foreach ($self[0]->attributes() as $key=>$value) {
   echo $key . ' - ' . $value . PHP_EOL;
}  

The JV solution worked perfectly. Thanks a lot for your help!

I was a bit stuck with that one.

Thanks Guido to have helped me on that issue.

You could also access the attributes directly, by name, rather than looping over them.


$link = $self[0];
$rel  = (string) $link['rel'];
$type = (string) $link['type'];
$href = (string) $link['href'];

var_dump($rel, $type, $href);

Wow, it is a excellent subjection. Thanks a lot Salathe.