Skip to main content
Published: January 30 2009, 3:01:00 PMUpdated: November 28 2020, 5:16:16 PM

I am using PHP to make API requests. Why do I see stray characters in my XML response?

The stray characters are indicators that the HTTP response is chunked which the PHP function employed is not able to handle.
So what is chunking?

HTTP 1.1 evolved to address new needs and overcome shortcomings of HTTP 1.0. Generally speaking, it is a superset of HTTP 1.0. One of the improvements over HTTP 1.0 is - Faster response for dynamically-generated pages, by supporting chunked encoding, which allows a response to be sent before its total length is known.

If a server wants to start sending a response before knowing its total length, it might use the simple chunked transfer-encoding, which breaks the complete response into smaller chunks and sends them in series. You can identify such a response because it contains the "Transfer-Encoding: chunked" header. All HTTP 1.1 clients must be able to receive chunked messages.

A chunked message body contains a series of chunks, followed by a line with "0" (zero), followed by optional footers (just like headers), and a blank line. Each chunk consists of two parts:

  • a line with the size of the chunk data, in hex and ending with CRLF.
  • the data itself, followed by CRLF.

Here is a sample chunked response.

 GET /LMS/GetJobStatus.php HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/, application/, application/msword, application/xaml+xml, application/, application/x-ms-xbap, application/x-ms-application, application/x-silverlight, application/x-silverlight-2-b2, application/x-shockwave-flash, */*
Accept-Language: en-us
UA-CPU: x86
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; WOW64; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727; InfoPath.1; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648)
Host: my-machine:8080
Connection: Keep-Alive

HTTP/1.1 200 OK
Date: Fri, 30 Jan 2009 21:48:17 GMT
Server: Apache/2.2.6 (Win32) PHP/5.2.4
X-Powered-By: PHP/5.2.4
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html

<?xml version='1.0' encoding='UTF-8'?><getJobsResponse xmlns:sct="" xmlns=""><ack>Success</ack><version>1.0.0</version><timestamp>2009-01-30T21:48:17.177Z</timestamp></getJobsResponse>


In some cases a server or client may want the older HTTP 1.0 behavior. In those circumstances a Connection: close header can be added to inform the receiving party that the persistent connection should not be used again. Alternatively you could use cURL because it supports the newer HTTP/1.1 standard. The other PHP functions do not.

How well did this answer your question?
Answers others found helpful