Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple JSON request in PHP

I have the following json

country_code({"latitude":"45.9390","longitude":"24.9811","zoom":6,"address":{"city":"-","country":"Romania","country_code":"RO","region":"-"}})

and i want just the country_code, how do i parse it?

I have this code

<?php
$json = "http://api.wipmania.com/jsonp?callback=jsonpCallback";
$jsonfile = file_get_contents($json);

var_dump(json_decode($jsonfile));
?>

and it returns NULL, why?

Thanks.

like image 735
Master345 Avatar asked Mar 29 '12 17:03

Master345


People also ask

How does PHP handle JSON request?

PHP File explained:Convert the request into an object, using the PHP function json_decode(). Access the database, and fill an array with the requested data. Add the array to an object, and return the object as JSON using the json_encode() function.

How pass JSON object in post request in PHP?

Send JSON data via POST with PHP cURLSpecify the URL ( $url ) where the JSON data to be sent. Initiate new cURL resource using curl_init(). Setup data in PHP array and encode into a JSON string using json_encode(). Attach JSON data to the POST fields using the CURLOPT_POSTFIELDS option.

How show JSON data from HTML table in PHP?

To use PHP function file_get_contents () we can read a file and retrieve the data present in JSON file. After retrieving data need to convert the JSON format into an array format. Then with the use of looping statement will display as a table format.

How can access JSON decoded data in PHP?

Reading JSON From a File or String in PHP First, you need to get the data from the file into a variable by using file_get_contents() . Once the data is in a string, you can call the json_decode() function to extract information from the string.


2 Answers

<?php
$jsonurl = "http://api.wipmania.com/json";
$json = file_get_contents($jsonurl);
var_dump(json_decode($json));
?>

You just need json not jsonp.
You can also try using json_decode($json, true) if you want to return the array.

like image 197
Solo Omsarashvili Avatar answered Sep 20 '22 14:09

Solo Omsarashvili


you're requesting jsonp with http://api.wipmania.com/jsonp?callback=jsonpCallback, which returns a function containing JSON like:

jsonpCallback({"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}})

and not JSON itself. change your URL to http://api.wipmania.com/json to return pure JSON like:

{"latitude":"44.9718","longitude":"-113.3405","zoom":3,"address":{"city":"-","country":"United States","country_code":"US","region":"-"}}

notice the second chunk of code doesn't wrap the json in the jsonpCallback() function.

like image 45
JKirchartz Avatar answered Sep 17 '22 14:09

JKirchartz