user6721269 user6721269 - 3 months ago 7
JSON Question

How to consume a json object in PHP

This may be simple to some but I am a newbie in PHP and json and was wondering how do I consume such a cURL below. Like save the data in a database in PHP. Anyone? Thank you.

curl -i \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-u username:password \
-d '{
"service_name" : "MPESA",
"business_number" : "888555",
"transaction_reference" : "DE45GK45",


}' \
"http://your_domain.com/transaction_consumer"

Answer

There are two steps to take: 1. load the JSON data 2. understand the JSON data 3. load the data in a database

Your code appears to load the JOSN data using curl. In my experience, curl is powerful but complex for beginners. Probable file_get_contents() http://php.net/manual/en/function.file-get-contents.php works as well and is more easy.

e.g. $json_data = file_get_contents("URL TO DATA");

Second, there are some JSON function in PHP. I like the json_decode function http://php.net/manual/en/function.json-decode.php. e.g. by using

$array = (json_decode($json_data, true));

to get the data in an array.

Third, this totale depends on the database setup (mysql?). Make sure you have a connection, a database and a table. Then you can use an insert query and insert the data from the $array.