Jump to content

[SOLVED] foreach SimpleXMLElement Object


fanfavorite

Recommended Posts

I have a variable ($img) with an array inside a SimpleXMLElement Object.  Here is the printed variable:

 

SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [src] => images/cclogos.gif
            [alt] => 
            [width] => 151
            [height] => 50
        )

)

 

I can get each value by using $img['src'], $img['width'], etc, however I want to use a foreach command to get all the keys (src,width, etc) and values (images/cclogo.gif,151,50).

 

I tried the following options with no success:

 

foreach ($img as $key=>$im) {

 

foreach ($img->{@attributes} as $key=>$im) {

 

I can't figure it out.  Any help is appreciated.  Thanks!

Link to comment
https://forums.phpfreaks.com/topic/142041-solved-foreach-simplexmlelement-object/
Share on other sites

I am not 100% familiar with the simple xml, and more code might help but I think this would work:

 

<?php
$string = <<<XML
<a xmlns:b>
<foo name="one" game="lonely">1</foo>
</a>
XML;

$xml = simplexml_load_string($string);
foreach($xml->foo[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}
?>

 

The above is an example taken from SimpleXML->atrribute  Hopefully that helps ya.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.