Cannot parse curl response as json - php

Here is my curl php code:
$ip=$cs[remoteip];
$remoteip = 'http://freegeoip.net/json/'.$ip;
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$remoteip);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$output=curl_exec($ch);
var_dump($output);die();
Here is the response:
string(250) "({"ip":"104.184.193.15","country_code":"US","country_name":"United States","region_code":"FL","region_name":"Florida","city":"Boynton Beach","zip_code":"33472","time_zone":"America/New_York","latitude":26.5253,"longitude":-80.0664,"metro_code":548});"
Now when I do this:
$output=json_decode($output);
curl_close($ch);
var_dump($output);die();
I get a NULL as the response.
I also tried json_decode($output,true) and got NULL as the result:
Not quite sure what to do here.

The json string has a wrong format! The first character '(' and the last two characters ');' should be removed.

Related

Get values from JSON data using PHP [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm using PHP to get a JSON response from a website and then process the response using json_decode. This is my PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.checkwx.com/taf/LLBG/?format=json");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'X-API-Key: 555555555'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close ($ch);
$json=json_decode($response,true);
$fulltaf = $json['status']['success']['data']['icao'];
This doesn't work.
This is the JSON data returned to be processed by json_decode:
{
"status": "success",
"data": [
{
"icao": "KPIE",
"observed": "07-03-2017 # 14:20Z",
"raw_text": "KPIE 071353Z 13017G23KT 10SM CLR 21\/13 A3031 RMK AO2 SLP262 T02060128",
"wind_degrees": 130,
}
]
}
You don't specify what didn't work?
First problem is that your JSON has a syntax error. I tried to validate your JSON using http://jsonlint.com and it flagged an extra comma after the 130 for wind_degrees. Check that actual response doesn't have that comma. The JSON won't parse properly with the extra comma.
The next problem is that data is an array (because its data is enclosed in brackets). In this example the array only has one element, [0], therefore to access icao you need to reference it as I show below.
My guess is that the following line didn't work correctly:
$fulltaf = $json['status']['success']['data']['icao'];
Based on the JSON you listed, this line should be the following if you want to retrieve the icao member of data.
$fulltaf = $json['data'][0]['icao'];
The following reference should return 'success' if you want to test for a successful response.
$json['status']

JSON_ERROR_CTRL_CHAR while using json_decode, none of the classic solutions work

I've been trying to fix this thing for an entire day already and couldn't get it to work. Something which is supposed to be easy.
The problem is, I do a GET request to this URL: http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b
Then, I try to convert the result to a JSON format using the PHP function json_decode. I do it like this:
$httpResponse = drupal_http_request('http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b');
$data = $httpResponse->data;
$datas = json_decode($data);
var_export($datas);
$error = json_last_error_msg();
echo "Error = $error";
And the error message returns "Control character error, possibly incorrectly encoded"
I have already tried using stripslashes, deleting BOM, html_entities, deleting some initial characters and none of them have worked.
You have to set "Accept-Encoding" header to "gzip, deflate", otherwise the response is truncated.
$httpResponse = drupal_http_request('http://api.champion.gg/stats?api_key=851a15d4f271849f3beee664ea03db3b', array('Accept-Encoding' => 'gzip, deflater'));
$data = gzdecode($httpResponse->data);

Cannot retrieve JSON POST via PHP: cURL

I tried implementing the following PHP code to POST JSON via PHP: cURL (SOME FORCE.COM WEBSITE is a tag that signifies the URL that I want to POST):
$url = "<SOME FORCE.COM WEBSITE>";
$data =
'application' =>
array
(
'isTest' => FALSE,
key => value,
key => value,
key => value,
...
)
$ch = curl_init($url);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, true);
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array
(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string)
)
);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
echo '<pre>';
echo $_POST;
$jsonStr = file_get_contents('php://input'); //read the HTTP body.
var_dump($jsonStr);
var_dump(json_decode($jsonStr));
echo '</pre>';
The output of the above is the following:
"Your TEST POST is correct, please set the isTest (Boolean) attribute on the application to FALSE to actually apply."
Arraystring(0) ""
NULL
OK, the above confirms that I formatted the JSON data correctly by using json_encode, and the SOME FORCE.COM WEBSITE acknowledges that the value of 'isTest' is FALSE. However, I am not getting anything from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". I decided to just ignore that fact and set 'isTest' to FALSE, assuming that I am not getting any JSON data because I set 'isTest' to TRUE, but chaos ensues when I set 'isTest' to FALSE:
[{"message":"System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing body, need at least one of html or plainText: []\n\nClass.careers_RestWebService.sendReceiptEmail: line 165, column 1\nClass.careers_RestWebService.postApplication: line 205, column 1","errorCode":"APEX_ERROR"}]
Arraystring(0) ""
NULL
I still do not get any JSON data, and ultimately, the email was unable to be sent. I believe that the issue is resulting from an empty email body because there is nothing coming from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". Can you help me retrieve the JSON POST? I would really appreciate any hints, suggestions, etc. Thanks.
I solved this question on my own. I was not sure if I was doing this correctly or not, but it turns out that my code was perfect. I kept refreshing my website, from where I am POSTing to SOME FORCE.COM WEBSITE. I believe that the people managing SOME FORCE.COM WEBSITE were having issues on their end. Nothing was wrong with what I did. For some reason, I got a code 202 and some gibberish text to go along with it. I would be glad to show the output, but I do not want to POST again for the sake of the people managing SOME FORCE.COM WEBSITE that I am POSTing to. Thank you guys for your help.

PHP: JSON format outputs into one long single line

here is my PHP script.
do2:locu alexus$ cat venuesearch.php
<?php
$KEY='XXXXXXXXXXXXXXX';
$URL='http://api.locu.com/v1_0/venue/search/?api_key=';
$ch=curl_init();
curl_setopt($ch, CURLOPT_URL, $URL.$KEY);
curl_setopt($ch, CURLOPT_HEADER,0);
print_r(json_decode(curl_exec($ch),TRUE));
?>
do2:locu alexus$
locu service provides output in JSON format. When I run script I'm getting output all in long single line.
sample of output:
do2:locu alexus$ php venuesearch.php
{"meta": {"cache-expiry": 3600, "limit": 25}, "objects": [{"categories": ["restaurant"], "country": "United States",..........
What am I missing? How can I access each of those variables? maybe it makes sense to convert it into XML?
* UPDATE * : .. in example #1 of PHP: json_decode - Manual shows formated output, if I use true then I get array, I'm not getting neither formatet output nor array.
Try adding:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
before execution.
It looks like the execution is simply printing the response rather than returning it as a string to be processed by json_decode.
You should look at the original data:
$json = curl_exec($ch);
var_dump($json);
Your described output is only possible if the API returns a json encoded json string, like that:
"{\"meta\": {\"cache-expiry\": 3600, \"limit\": 25}, \"objects\": [{\"categories\": [\"restaurant\"], \"country\": \"United States\",.......... '
(note the outer quotes, they are part of the string)
This is very weird and definitly a bug in the API but the only way to get around it is to decode it twice:
$data = json_decode(json_decode($json));
Edit: Forget that, Stegrex has figured it out.

Looping through query links via CURL and merging result arrays in PHP

The following code is supposed to search for a term on twitter, loop through all the result pages and return one big array with the results from each page appended at each step.
foreach($search_terms as $term){
//populate the obj array by going through all pages
//set up connection
$ch = curl_init();
// go through all pages and save in an object array
for($j=1; $j<16;$j++){
$url ='http://search.twitter.com/search.json?q=' . $term .'&rpp=100&page='.$j.'';
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$var[$j] = curl_exec($ch);
curl_close($ch);
$obj = array_merge((array)$obj,(array)json_decode($var[$j], true));
}
}
It doesn't quite work though and am getting these errors:
curl_setopt(): 3 is not a valid cURL handle resource
curl_exec(): 3 is not a valid cURL handle resource
curl_close(): 3 is not a valid cURL handle resource
...... and this is repeated all the way from 3-> 7...
curl_setopt(): 7 is not a valid cURL handle resource
curl_exec(): 7 is not a valid cURL handle resource
curl_close(): 7 is not a valid cURL handle resource
//set up connection
$ch = curl_init();
// go through all pages and save in an object array
for($j=1; $j<16;$j++){
You need the call to curl_init() inside your loop since you close it at the end of each iteration.

Categories