Klanestro
Klanestro

Reputation: 3225

jsonp -> json_decode()

for some reason I can't get the information out of a returned jsonp string,

<?php
// Created by Talisman 01/2010 ★✩ 

$vorto = $_GET['vorto']; // Get the Word from Outer Space and Search for it!

if (isset($vorto))
 {
 echo $vorto;
 } else {
  $Help = "No Vorto -> add ?vorto=TheWordYouWant to the end of this website";
  echo $Help;
 }



// Now Lets Search Alex's Vortaro, It uses jsonp
// ex. http://vortaro.us.to/ajax/epo/eng/petas/?callback=?
// Future Feature inproved language functinality

$AVurl1 = "http://vortaro.us.to/ajax/epo/eng/"; 
$AVurl2 = "/?callback=";
$AVfinalurl= $AVurl1 . $vorto . $AVurl2;

echo $AVfinalurl . ' </br> '; // DEBUG CODE 

$AVcontent = file_get_contents($AVfinalurl) ;
echo $AVcontent . ' </br> ';   // DEBUG CODE 

// ★✩ Why does this next line not work?

 $AVDecode = json_decode($AVcontent);


// /* 
  if(isset( $AVcontent)) {          // DEBUG CODE
  echo "json_decode set AVcontent" . ' </br> ';
  } else {
  echo "something fishy here" . ' </br> ';
  }

 if (empty($AVcontent)){
  echo "EMPTY EMPTY" . ' </br> ';
  } else {
  echo "Not Empty". ' </br> ';
  }

echo $AVDecode . ' </br> ';
// */

// Why can't I echo or access information with $AVDecode? Is it something with
// jsonp?

?>

this is my results

komputilojhttp://vortaro.us.to/ajax/epo/eng/komputiloj/?callback=

({"text":"komputilo: computer"})

json_decode set AVcontent

Not Empty

I should be seeing the echo $AVDecode

Upvotes: 2

Views: 6925

Answers (3)

Pekka
Pekka

Reputation: 449713

Debugging suggestion:

Check the output of json_last_error(). It should give you an exact reason why it doesn't work. Available from PHP 5.3.0 only, though.

The reason:

JSONP is not identical with JSON. It contains extra data that breaks json_decode().

Solution:

Remove the extra brackets using substr($AVDecode, 1, strlen($AVDecode)-2)

Upvotes: 6

Daff
Daff

Reputation: 44215

Your example URL returns

?({"text":"<b>peti</b>: ask, ask for, beg, bid, request"})

JSONP is not valid JSON, it will wrap it into your supplied callback like

callbackname(JSONIsInHere)

So you need to substring $AVcontent from the first occurrence of ( to the the last ocurrence of ) so that you will get the callback parameter which is valid JSON and can be encoded with json_decode.

Upvotes: 0

antpaw
antpaw

Reputation: 16015

you cant echo an object or an array. please tell us what this line prints out:

print_r(json_decode($AVcontent));

place it right after the $AVDecode = json_decode($AVcontent);

Upvotes: 0

Related Questions