2

I am trying to convert some xml into a json object using PHP.

This should be working, yet for some bizarre reason it is failing.

Could someone provide some input.

// Loop Through images and return the right one.
$i = 1;
foreach($page->image as $image) {
    if ($i == $_GET['id']) {
         echo json_encode(array(
            'background' => $image['bgColor'],
            'image' => $image['source'],
            'caption' => $image['caption']
         ));
    }
    $i++;
}

This code returns the following.

{"background":{"0":"000033"},
 "image":"0":"0210e849f02646e2f5c08738716ce7e8b3c1169112790078351021245495.jpg"},
 "caption":   {"0":"Frog"}}

print_r($image['bgColor']); shows 'SimpleXMLElement Object ( [0] => 000033 )'

echo $image['bgColor']; shows '000033'

How do I parse values like the echo statement instead of the print_r statement. Why are these different?

hakre
  • 193,403
  • 52
  • 435
  • 836
ComputerUser
  • 4,828
  • 15
  • 58
  • 71
  • Why are you using print_r when you don't seem to understand what it actually does? print_r() displays information __about__ a variable – Mark Baker Jul 13 '10 at 11:53
  • An example that namespaced children are not displayed in `print_r` is in: [SimpleXML and print_r() - why is this empty?](http://stackoverflow.com/q/3109302/367456) – hakre May 02 '13 at 13:55

1 Answers1

3

Why are these different

Because these variables are not strings internally, but SimpleXMLElement type objects that get converted into strings when output by echo.

To use the values elsewhere,I usually do an explicit cast:

$bg_color = (string) $image['bgColor'];

A canonical question regarding casting a simplexml element into a string is here:

Community
  • 1
  • 1
Pekka
  • 442,112
  • 142
  • 972
  • 1,088