I’m trying to get the json data from the following url:
https://chart.googleapis.com/chart?cht=gv&chl=digraph framework { 1[color=red]; 2; 3[color=red]; 4; 5; 6; 7; 8; 9; 10; 11; 12[color=red]; 13; 14[color=red]; 15; 16[color=red]; 17[color=red]; 2 -> 1; 3 -> 1; 4 -> 1; 5 -> 1; 6 -> 2; 8 -> 9; 9 -> 8; 12 -> 2; 12 -> 3; 12 -> 4; 12 -> 5; 7 -> 6; 7 -> 10; 7 -> 11; 8 -> 7; 13 -> 5; 14 -> 13; 15 -> 6; 16 -> 15; 17 -> 12; 10 -> 4; 11 -> 3; 14 -> 16; 16 -> 17; }&chof=json
I have tried several methods that were suggested in other questions:
$jsonurl = "https://chart.googleapis.com/chart?cht=gv&chl=digraph framework { 1[color=red]; 2; 3[color=red]; 4; 5; 6; 7; 8; 9; 10; 11; 12[color=red]; 13; 14[color=red]; 15; 16[color=red]; 17[color=red]; 2 -> 1; 3 -> 1; 4 -> 1; 5 -> 1; 6 -> 2; 8 -> 9; 9 -> 8; 12 -> 2; 12 -> 3; 12 -> 4; 12 -> 5; 7 -> 6; 7 -> 10; 7 -> 11; 8 -> 7; 13 -> 5; 14 -> 13; 15 -> 6; 16 -> 15; 17 -> 12; 10 -> 4; 11 -> 3; 14 -> 16; 16 -> 17; }&chof=json"
//Method 1
$json = file_get_contents($jsonurl);
// returns an error from the google page: 400. That’s an error. Your client has issued a malformed or illegal request. That’s all we know
//Method 2
$curlSession = curl_init();
curl_setopt($curlSession, CURLOPT_URL, $jsonurl);
curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true);
curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true);
$json_decoded = json_decode(curl_exec($curlSession));
curl_close($curlSession);
// returns NULL
// This makes sense if the JSON isn't not returned correctly. I think json_decode() returns NULL if the input is not correct json data.
//Method 3
$json = file_get_contents(urlencode($jsonurl));
// Gives another error: [function.file-get-contents]: failed to open stream: File name too long
If I just post the raw JSON data in my code the rest of my algorithm works fine. The point is, in my actual code the url is dynamic and I need to be able to get the JSON data from the url.
It seems like an security issue with google. However, I don’t have a clue as of how to solve this.
This is my first question on Stackoverflow. Please let me know if you want to know more/if I should edit my question somehow.
Thanks in advance!
Your URL needs to be URI-escaped for cURL to use it properly. If I change your script to this:
Then
$jsoncontains the data object I would expect. I tested this in PHP 5.3.15 on a Mac.