Simplexml_load_string() fail to parse error

Simplexml_load_string() fail to parse error

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

Stefan Bogdanescu

Founder & Senior Architect

Simplexml_load_string() fail to parse error

When dealing with external APIs, especially those returning non-English content, you often encounter parsing errors that stem from encoding mismatches rather than structural issues in your code. A classic example involves loading a Google Weather API response for a Chinese locale (hl=zh-CN). Attempting to feed the raw HTTP response directly into simplexml_load_string() frequently results in a parser error indicating that the input is not proper UTF-8.

The specific error message usually points to invalid byte sequences, such as Input is not proper UTF-8, indicate encoding! Bytes: 0xB6 0xE0 0xD4 0xC6. This happens because PHP's SimpleXML parser expects valid UTF-8 by default when no encoding declaration is present in the XML root element. If the response declares a different charset or contains bytes that are valid in another encoding (like GBK), the parser fails immediately upon encountering the first invalid byte sequence according to UTF-8 rules.

The core issue lies in how file_get_contents() retrieves data versus how the SimpleXML library interprets it. When you fetch content via file_get_contents(), PHP returns a raw string based on the server's response headers. If the server sends Content-Type: text/xml; charset=GBK or similar, but your parser assumes UTF-8, the byte stream is misinterpreted.

Detecting and Correcting Encoding

To resolve this, you must explicitly tell the XML parser how to interpret the incoming bytes. You can do this by passing a second argument to simplexml_load_string(), which specifies the encoding name. If the server response includes an XML declaration like <?xml version="1.0" encoding="GBK"?>, SimpleXML will automatically handle it correctly if you don't override the input. However, if the parser defaults to UTF-8 and the source is GBK, you need to force the conversion before parsing or pass the correct encoding name explicitly.

Here is an adjusted approach assuming the response is in GBK but needs to be parsed as such:

$googleData = file_get_contents('http://www.google.com/ig/api?weather=11102&hl=zh-CN');

// Explicitly tell SimpleXML the expected encoding if it differs from UTF-8
$xml = simplexml_load_string($googleData, 'SimpleXMLElement', LIBXML_NOCDATA, 'GBK');

Alternatively, if you want to standardize everything to UTF-8 before parsing (which is often safer for subsequent string manipulation), you can use mb_convert_encoding:

$rawData = file_get_contents('http://www.google.com/ig/api?weather=11102&hl=zh-CN');

// Detect encoding from headers if available, or assume GBK for zh-CN responses
if (mb_detect_encoding($rawData, 'UTF-8', true) === false) {
    $rawData = mb_convert_encoding($rawData, 'UTF-8', 'GBK');
}

$xml = simplexml_load_string($rawData);

Handling the XML Declaration

Another common pitfall is ignoring the XMLDeclaration in the response. If the API returns valid UTF-8 but includes an encoding declaration that contradicts reality (e.g., claiming GBK while sending UTF-8 bytes), SimpleXML will try to re-encode the document based on that declaration, potentially corrupting the data or triggering warnings.

To bypass this entirely and treat the input strictly as raw bytes without interpreting the XML header's encoding hint, you can use the LIBXML_NOBLANKS flag combined with explicit UTF-8 handling. However, the most robust solution for international APIs is to ensure the response is converted to UTF-8 before passing it to SimpleXML, regardless of what the XML declaration says.

Best Practices for API Integration

When building applications that consume international weather or map data, relying on simplexml_load_file() or simplexml_load_string() without encoding checks is a fragile pattern. The parser is strict; it will not guess the encoding. Always verify the Content-Type header returned by the API. If the header indicates a non-UTF-8 charset, you must convert the string manually before parsing.

In modern PHP applications using frameworks like Laravel, this logic can be encapsulated in a service class to prevent duplication and ensure consistent handling of international data sources. For instance, you might create a dedicated method that detects the encoding from the response headers or makes an educated guess based on the Accept-Language parameter used in the request URL.

Remember that SimpleXML is not designed for complex binary data or highly non-standard encodings without explicit guidance. If the API response is malformed or uses legacy encodings like GB2312 or Shift_JIS, you may need to use a more flexible parser like DOMDocument with LIBXML_NOERROR, though this comes with its own trade-offs regarding memory usage and ease of access.

Ultimately, the error "Input is not proper UTF-8" is a signal that your byte stream does not match the parser's expectations. Addressing it requires either correcting the source data or explicitly configuring the parser to accept the incoming format.

Our network