Sending XML data using HTTP POST with PHP

Sending XML data using HTTP POST with PHP

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sending XML Data Using HTTP POST with PHP

Sending a payload like that XML document to a third-party SMS gateway isn't just about string concatenation; it's about managing HTTP headers, character encoding, and ensuring the server processes the body exactly as the client expects. When a service listens for POST requests, the data must arrive in the request body, not appended to the query string. If you send that XML via a GET request or without setting the correct Content-Type header, the gateway will likely reject it immediately.

In PHP, specifically within frameworks like CodeIgniter, the mechanism to handle this depends heavily on how your controller method is defined and whether you are using raw file pointers or HTTP helper classes. The most robust approach for modern PHP development involves leveraging the HTTP_REQUEST class found in the standard library (available since PHP 7.0) or, for legacy CodeIgniter versions, the built-in $this->load->helper('url') combined with form processing logic.

Constructing the Request Body

The XML provided uses a CDATA section to wrap the SMS content: <![CDATA[This is a test æøå ÆØ]]>. This is critical because it tells the XML parser to treat everything inside those tags as literal text, preventing issues with special characters like quotes or ampersands breaking the syntax.

When constructing the POST body in PHP, you must ensure that the variable holding this XML string is treated as a raw blob of data. You cannot simply echo it without care if there are any potential encoding mismatches between your PHP environment and the gateway. The gateway expects UTF-8, so your PHP file's encoding (often defined in the first line as <?php ... ?> or via Apache/Nginx headers) must align with that, although for string manipulation, PHP handles this internally well if you are using UTF-8 source files.

Here is how you might construct the request body within a CodeIgniter controller:

$xml_payload = '<?xml version="1.0" encoding="UTF-8"?>
<gate>
   <country>NO</country>
   <accessNumber>1900</accessNumber>
   <senderNumber>1900</senderNumber>
   <targetNumber>4792267523</targetNumber>
   <price>0</price>
   <sms>
      <content><![CDATA[This is a test æøå ÆØ]]></content>
   </sms>
</gate>';

// Define the headers explicitly before sending
$headers = [
    'Content-Type: application/xml',
    'Content-Length: ' . strlen($xml_payload)
];

// In CodeIgniter, you can use $this->load->helper('url') and create a cURL request
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $sms_gateway_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$response = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);

Why application/xml Matters

Notice the Content-Type: application/xml header. This is not optional. HTTP is a protocol built on negotiation; the server decides how to parse the incoming stream based on this header. If you send text/plain, the gateway might try to read the first line as a simple string and fail when it hits the opening <gate> tag, or worse, treat the entire body as garbage data.

Some legacy gateways are notoriously strict about Content-Length. When using curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_payload), PHP calculates the length automatically, but explicitly setting the Content-Length header ensures compatibility with servers that read headers first and then validate the body size before accepting any data transfer. Skipping this step can lead to timeouts or "request too large" errors even if your payload is tiny.

Handling the Response

Once you send the POST request, you must handle the response carefully. SMS gateways typically return an XML response indicating success or failure. You should parse this response to determine if the message was queued successfully. If $http_code is not 200, check the content of $response for error codes like 503 (Service Unavailable) or specific gateway error tags.

Trade-offs and Pitfalls

One common mistake developers make is forgetting that the XML declaration at the top (<?xml version="1.0" encoding="UTF-8"?>) must match the actual encoding of the data. If your PHP file is saved as UTF-16 or contains hidden BOM characters, the gateway will reject the payload. Always ensure your source code files are saved as UTF-8 without BOM.

Another pitfall is using file_get_contents() to read the response if the gateway supports streaming or expects a specific callback mechanism. While curl provides full control over headers and timeouts, relying on file_get_contents('http://...', true, $context) with a custom context created via stream_context_create can be a cleaner alternative in CodeIgniter if you prefer not to initialize cURL resources manually.

For example:

$context = stream_context_create([
    'http' => [
        'method'  => 'POST',
        'header'  => "Content-Type: application/xml\r\n" .
                     "Content-Length: " . strlen($xml_payload) . "\r\n",
        'content' => $xml_payload,
    ]
]);

$response = file_get_contents($sms_gateway_url, false, $context);

This approach achieves the same result but requires you to manually manage the Content-Length header string, which is prone to errors if the payload changes dynamically. Using cURL is generally safer for production environments where precision is required.

If you are working within a larger application ecosystem and need more flexibility, consider evaluating modern PHP frameworks that offer better abstractions for HTTP client requests, such as those provided by LaravelCompany.com, which can simplify complex request handling and response parsing significantly. However, for the specific task of sending raw XML to a legacy gateway, mastering curl or stream contexts remains the most direct and reliable path.

Our network