acemasta acemasta - 7 months ago 22
PHP Question

PHP: SimpleXML and Arrays

When I run this code:

foreach($xml->movie as $movie) {
if(isset($movie->photos)) {
foreach ($movie->photos as $photo) {
echo $photo." ";
}
echo "<hr/>";
}
}


I get nice output of the actual data, e.g. a row looks like


06397001.jpg 06397002.jpg 06397003.jpg 06397004.jpg 06397005.jpg


But when I throw it in an array, it includes all the SimpleXML wrapper tags and the jpgs are not at the root of the array.

code:

foreach($xml->movie as $movie) {
if(isset($movie->photos)) {
$photos = array();
foreach ($movie->photos as $photo) {
$photos[] = $photo;
}
} else $photos = "";
var_dump($photos);
echo "<hr />";
}


e.g. same row looks like

array(5) {
[0]=> object(SimpleXMLElement)#11 (1) {
[0]=> string(12) "06397001.jpg"
}
[1]=> object(SimpleXMLElement)#12 (1) {
[0]=> string(12) "06397002.jpg"
}
[2]=> object(SimpleXMLElement)#13 (1) {
[0]=> string(12) "06397003.jpg"
}
[3]=> object(SimpleXMLElement)#14 (1) {
[0]=> string(12) "06397004.jpg"
}
[4]=> object(SimpleXMLElement)#15 (1) {
[0]=> string(12) "06397005.jpg"
}
}


Why is this happening/how can I remove this so I just get an array of the photos at root level like when I echo it?

Answer

SimpleXMLElement results look like simple objects and arrays, but do some magical things that normal objects and arrays can't do. It's designed this way so that you can use less code.

You can probably solve your problem with something like:

foreach($xml->movie as $movie) { 
  if(isset($movie->photos)) {
    $photos = array();
    foreach ($movie->photos as $photo) {
      $photos[] = "$photo"; 
      // or you could use, I believe: $photos[] = $photo[0] 
    }
  } 
  else $photos = "";
  var_dump($photos); echo "<hr />";
}

Why is this happening? Because a SimpleXML element when treated as a string will behave as if it's a string, with the value being that element's text contents. In your first example, the use of echo was treating the element as a string so it just returned the string.

Comments