Hello! Can you please tell me how to parse the values ​​of the json file that is wrapped in a callback?

I get the value like this:

$json = file_get_contents('https://geoip-db.com/jsonp/00.000.00.00'); $data = json_decode($json); 

The resulting value itself:

 callback({"country_code":"RU","country_name":"COUNTRY","city":"CITY","postal":null,"latitude":00.0000,"longitude":00.0000,"IPv4":"00.000.00.00","state":" REGION'"}) 

Only country_name, city, state are needed

  • it seems here it remains only to delete the function name and the bracket, and then transfer to json_decode what is left - dizballanze
  • I tried, but I don’t understand how to do it - Elizabeth
  • and is there another option? - Elizabeth

2 answers 2

For one level of nesting, you can.

 $json = file_get_contents('https://geoip-db.com/jsonp/00.000.00.00'); preg_match_all("/\{.*\}/",$json,$data2); $data = json_decode($data2[0][0]); echo $data->IPv4; 
  • Thanks a lot, it helped! - Elizabeth

You can cut the call using a regular expression /^\w+\((.*)\)$/
We simply skip the identifier (the name of the function) and the parentheses and grab everything that is left (the desired json).

The JSON in question is invalid, 00.00000 is not a valid number.

Feeddle

 <?php $json = 'callback({"country_code":"RU","country_name":"COUNTRY","city":"CITY","postal":null,"latitude":0.0000,"longitude":0.0000,"IPv4":"00.000.00.00","state":" REGION\'"})'; preg_match('/^\w+\((.*)\)$/', $json, $match); if (!$match) die('Malformed JSONP'); $data = json_decode($match[1], true); if (!$data) die ('Malformed JSON'); var_dump($data); 

In case the source JSON can be multi-line, you need to modify the regular expression to capture any characters (including line breaks).

For example:

 '/^\w+\(([\s\S]*)\)$/m' 
  • 0000 I wrote for the place of IP or other numbers. course the meanings will be different - Elizabeth
  • I'm "latitude":00.0000 about "latitude":00.0000 in the body of json in question - vp_arth