How to Consume XML Rest API Using PHP

This lumen tutorial help to create a rest wrapper using lumen to consume XML type Rest API. I have already shared a tutorial to consume JSON type rest API but this example will use XML type rest service that sends XML as a response.

XML is another popular data format to read input and send response output using web-service. The XML format can be used for rest or SOAP type web service.

I am using the lumen framework to consume XML type restful web service. If you are not familiar with lumen or laravel, please read the below tutorials:

You can also use the same mechanism for CURL or other rest PHP frameworks.

You can also check other recommended tutorials of Lumen/Laravel,

We will create a client wrapper for the rest server. We will use webservice host url and set header information.

$client = new Client([
    // Base URI is used with relative requests
    'base_uri' => 'restapi url', //https://hostname/api/
    // You can set any number of default request options.
    'timeout'  => 2.0,
	'headers' => ['Content-Type' => 'application/json', "Accept" => "application/json"],
    //ssl false
    'verify' => false
]);

We will pass XML rest endpoints to the client get method and get rest response body content,

$response = $client->get("computer/api/xml")->getBody();

Now we will parse XML data and convert it into JSON data using json_encode. For data processing, I have converted JSON into PHP array using json_decode method.

$xml = simplexml_load_string($response);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Leave a Reply

Your email address will not be published. Required fields are marked *