mcan
mcan

Reputation: 2082

Json encoding a image link

I have a json encoding problem.

If I print $r['image'] it prints alright. However if I print encoded json object there is a problem.

<?php
    echo 'it prints: '.$r['image'];
    //it prints: http://userserve-ak.last.fm/serve/126/90145859.jpg

    $jsonObj = json_encode($r);
    echo 'it prints: '.$jsonObj;
?> 

 {"artist_name":"atlanta rhythm section","track_name":"so into you","image":{"@attributes":{"size":"medium"}}} 

What is the part {"@attributes":{"size":"medium"}}? and why can I not see the image link in that place? What i have to do to see "image":http://userserve-ak.last.fm/serve/126/90145859.jpg on json object?

var_dump($r); is:

array(3) {
  ["artist_name"]=>
  string(22) "atlanta rhythm section"
  ["track_name"]=>
  string(11) "so into you"
  ["image"]=>
  object(SimpleXMLElement)#12 (1) {
    ["@attributes"]=>
    array(1) {
      ["size"]=>
      string(6) "medium"
    }
  }
}

I have tried url encoding the parameter $r['image'] but it has not help.

Upvotes: 0

Views: 3007

Answers (4)

Arend
Arend

Reputation: 3771

I think $image is an simplexmlobject. Which contains more information, but does not contain it's body, something is written about that here:

PHP, json_encode, json_decode of SimpleXML Object

A simple workaround can be

<?php
$r['image_url'] = (string) $r['image'];
?>

This will force the output, just in the same way you do by echoing the object in a string.

Upvotes: 1

Alexandre Danault
Alexandre Danault

Reputation: 8682

You can force the type to string by casting it:

print json_encode(array('image' => (string)$r['image']));

Result:

"image":http://userserve-ak.last.fm/serve/126/90145859.jpg

Upvotes: 1

Sundar
Sundar

Reputation: 4650

//This gives the image

<?php 

//form the array
$data['val']="http://userserve-ak.last.fm/serve/126/90145859.jpg";

//encode json
$encode = json_encode($data);

echo $encode;

//decode the json 
$decode = json_decode($encode);

//print the image
echo "<img src='".stripslashes($decode->val)."'>";

Upvotes: 1

Nabeel Arshad
Nabeel Arshad

Reputation: 487

use slashes before encoding json

$r['image'] = addslashes ($r['image'] );
 json_encode($r);

This might Help

Upvotes: 0

Related Questions