Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing response from a HTTP web service (JSON) in PHP

I need to consume a HTTP Web Service whose response in JSON format. How can i achieve this in php given the URL of the web service is known ?

like image 419
Ankit Rustagi Avatar asked Dec 05 '22 10:12

Ankit Rustagi


2 Answers

This is what you should do:

$data = file_get_contents(<url of that website>);
$data = json_decode($data, true); // Turns it into an array, change the last argument to false to make it an object

This should be able to turn the JSON data into an array.

Now, to explain what it does.

file_get_contents() essentially gets the contents of a file, either remote or local. This is through the HTTP portal, so you are not violating the privacy policy by using this function for remote content.

Then, when you use json_decode(), it normally changes JSON text to an object in PHP, but since we added true for the second argument, it returns an associative array instead.

Then you can do anything with the array.

Have fun!

like image 170
Lucas Avatar answered Dec 09 '22 15:12

Lucas


you need to json_decode() the response and then you have it as a php array to process it

like image 40
harikrish Avatar answered Dec 09 '22 14:12

harikrish