
For a customer project, we needed to do a jSON query with PHP. So I searched the web for a tutorial how to do, but I’ve found much about the PHP jSON functions, but not much how to make requests to jSON interfaces with PHP. So I try to explain you how it works.
Sending Data with PHP to a jSON Script with curl
To get the data we use the PHP curl functions. In our example we have added a authentication with curl, if not needed, just leave the lines, commented with // authentication.
[php]
// jSON URL which should be requested
$json_url = ‘http://www.mydomain.com/json_script.json’;
$username = ‘your_username’; // authentication
$password = ‘your_password’; // authentication
// jSON String for request
$json_string = ‘[your json string here]’;
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_USERPWD => $username . “:” . $password, // authentication
CURLOPT_HTTPHEADER => array(‘Content-type: application/json’) ,
CURLOPT_POSTFIELDS => $json_string
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
[/php]
The result will be a jSON string.
Normally you have to send a jSON string to the jSON URL and you will get a jSON string back. To encode your data, just use the php jSON functions. Use json_encode to create a json string from your PHP array and use json_decode to transform the jSON string to PHP array.
rasrmasr says:
Thanks for sharing!!
Url Opener says:
function UrlOpener($url){
global $output;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;
}
You can use this function to get content use curl url php. Sample here: http://urlopener.mixaz.net/
Put URL on form and get content
Thanks
alon says:
thank you very much. that helped me a lot!
Logo Vector says:
Great!
Simple, Clean and very Helpful
Rob Selleck says:
Exactly what I was looking for. Works great. Thanks dude
Jordan says:
Thanks a lot!
Guillaume says:
Thanks very much, it helps me a lot for querying open.sen.se
Nate says:
Thanks man, exactly what I needed!
For anyone else using json_decode after this, be sure to say $array = json_decode($result, true) otherwise it will return an object, and you wont be able to use it like a regular PHP array.
N Singh says:
This is great article…..its help me
Anas Mir says:
is There any way to read without curl?
Sven Wagener says:
@Anas Mir
Sorry Anas, but I can’t help you. I only know the curl method.
Richard says:
How to read JSON with php from this url:
http://api.master18.tiket.com/search/flight?d=PDG&a=CGK&date=2012-11-30&adult=1&child=1&infant=0&token=e3c3954731a96df7b54b73d38961b08b
Deepanshu kakkar says:
you have to use for loop here . For loop will iterate the array. Foreach loop is not successful here.
Deepanshu kakkar says:
Just like :
$i = 0;
for($i = 0; $i<count($fileData); $i++)
{
echo "”;
echo “”.$fileData[$i]->NameOfCompany.””;
echo “”.$fileData[$i]->Address.””;
echo “”.$fileData[$i]->City.””;
echo “”.$fileData[$i]->State.””;
echo “”.$fileData[$i]->ZipCode.””;
echo “”.$fileData[$i]->Phone.””;
echo “”.$fileData[$i]->Established.””;
echo “”.$fileData[$i]->Website.””;
echo “”.$fileData[$i]->GooglePlacesURL.””;
echo “”.$fileData[$i]->Category.””;
echo “”.$fileData[$i]->EmailAddressForListingsandReporting.””;
echo “”.$fileData[$i]->AbouttheBusiness.””;
echo “”.$fileData[$i]->FeaturedSpecial.””;
echo “”;
$i++;
}
Sven Wagener says:
Sorry, but this is no JSON and no standard.
Acca says:
I should show a request:
include( “json.php?q=KEYWORD” ); <— Is not possible.
How can I do?
Thanks
Sven Wagener says:
You can’t include a file with a parameter after it in that way. You have to open the file with the full URL like http://yourdoman.com/json.php?q=Keyword to get your values with such parameters.
Also you can’t use the include function for it. You can use the fopen function.
http://php.net/manual/en/function.fopen.php
But be sure that url fopen is not blocket on your server.
mauro says:
thanks, very neat without all php classes to be installed!!!
joe says:
You saved my lot of headache, thanks
Victor says:
very bad, there’s no curl_close($ch);
You should tell people that they must close the curl after opening it.
Shashi kanth says:
Thanks for sharing this snippet. Works awesome.
Sohail Sheikh says:
Below are Request & Response given in API document.
Example Request
curl -X GET
-H “X-Auth-Token: 6c602fc6b93d0c4b4797d6481d408f17″
“http://api.pcsbeacon.com/v1/collections ”
Example Response
[
{
“collection_id”: 123,
“name”: “The Lewis Carroll Collection”
},
{
“collection_id”: 156,
“name”: “Classics: Machiavelli”
}
]
When i try its not working for me its give me invalid token or say Service Unavailable.
Token detail:—
{“access”:{“token”:{“id”:”1c92bf205279177c4fdece41e440fc48″,”expires”:”Wed, 12 Jun 2013 11:43:03 +0000″}}}
i will give my code which i used for that.
$data = array(“X-Auth-Token” => ’1c92bf205279177c4fdece41e440fc48′);
$data_string = json_encode($data);
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,’http://api.pcsbeacon.com/v1/collections’);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
‘Content-Type: application/json’,
‘X-Auth-Token: 1c92bf205279177c4fdece41e440fc48′,
‘Content-Length: ‘ . strlen($data_string)
)
);
if(curl_exec($ch) === false)
{
echo ‘Curl error: ‘ . curl_error($ch);
}
else
{
echo ‘Operation completed without any errors’;
}
$result = curl_exec($ch);
print_r($result);
Please reply me as soon as possible..
Thanks
Sergey says:
+1 thanks
Raheel Shan says:
Your article is quite good but there is one thing confusing. When i need to send a large json string it is not sending. How can i resolve this problem. Here is the output of json encoded string.
{
“date”: “2013-06-19 05:38:00”,
“encrypted_string”: “7Y4jqgIfhj25ghsF8yJ/qTtzXafTtIlwsz7xWIDVWJGoF22X2JbfSWfQtgmI1dYyyJDgs3nmaWctTEgKW5VmHw==”,
“id”: 231,
“source_ref”: “testreference”,
“status”: “Active”
}
php newbie says:
how do you get posted values on the server side ?
Paul says:
Thank you dude, your a complete legend
aisha says:
thanks for sharing
logovectors says:
I used to get the json data using plain php and found it to be really slow, used this method here and yeah the speed up a bit
Ankush Jetly says:
to handle json/XML post data we need to use read only php:://input stream instead of http_raw_post_data normal post you can not handle!!!
Eduardo Serra says:
Fantastic! nicely done! thank you very much!
soboth says:
Cool, could you help me about Method Post, I want to make POST method to send data.
Abelardo says:
Hi,
$ch = curl_init($url); // URL returns a json
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$manage = json_decode($data);
echo $manage;
outputs:
– Recoverable fatal error: Object of class stdClass could not be converted to string in…
How could I obtain an array object?
Nice tutorial and thanks for your time!
Best regards.
Septiana says:
I try to get api game list from igdb but I got blank page with code above..
How I can get username auth and pass auth? Thanks!
Php On Web says:
Hi dude, i have also find out one good example
Curl GET And POST Method Calls – PHP Example