Getting jSON Data with PHP (curl method)

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.

 

What Do You Think?