The following post will explain how to use PHP/cURL to retrieve data in JSON or XML and process it for using in your PHP application

cURL is a command line tool that uses URL syntax to transfer data to and from servers. cURL is extremely flexible and can be used to transfer all sorts of data over various connections. In this example we’ll be using a HTTP request over SSL with a key and host value sent in the headers.

$ch = curl_init();

First initialise your cURL request.

$optArray = array(
    CURLOPT_URL => 'https://example.com/api/getInfo/',
    CURLOPT_RETURNTRANSFER => true
);

Then set the request options, this request will load the contents of https://example.com/api/getInfo.

$headers = [
    "Access-Key: 123456789QWERTYUIOP",
    "Access-Token: ASDFGHJKL0987654321",
];

Then send the headers, in this instance the headers include two values “Access-Key” and “Access-Token” these will be used by example.com to verify the request is coming from the right source.

curl_setopt_array($ch, $optArray);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

Next the options and headers are added to the cURL request, and the request is executed. The result of the request will be stored in $result.

If the value that is returned is in JSON format we’ll need to convert it from JSON into a PHP object:

$processed = json_decode($result, true);

Alternatively, if it is in XML the following code can be used:

$processed = simplexml_load_string($result);

The $processed variable will now contain our PHP object, ready for processing.

Full Code

Hello, I'm Keith, a website developer in Belfast, Northern Ireland working with PHP, Magento, Shopify and WordPress.

I've been building websites for over 10 years, from custom website development to bespoke web applications, Shopify and Magento ecommerce and Online Leaning Environments. I've worked on a range of projects and am always looking out for the next interesting project.

Related PHP Posts

Google Sheets to PHP Array

This PHP function accepts a public Google Sheets URL and converts it into a PHP array. You can use the array to either display the... August 2021 · PHP

PHP cURL Requests with JSON or XML

The following post will explain how to use PHP/cURL to retrieve data in JSON or XML and process it for using in your PHP application... March 2021 · PHP

Global Payments: Strong Customer Authentication (SCA) and 3D Secure 2

The roll out of 3D Secure 2 has been a long drawn-out process not helped by the COVID–19 pandemic. Part of the update has included... February 2021 · PHP

More PHP Posts...