Skip to content
PHP Logo

How can PHP developers effectively use cURL to handle API communication with XML data?

To effectively handle API communication with XML data using cURL in PHP, developers can set the appropriate headers, specify the request method, and include the XML data in the request body. They can then send the request to the API endpoint and retrieve the XML response for further processing.

php
$url = 'https://api.example.com/endpoint';
$xml_data = '<xml><data>Hello World!</data></xml>';

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);

$response = curl_exec($ch);

curl_close($ch);

// Process the XML response
$xml_response = simplexml_load_string($response);