22 Jul

PHP UTF-8 and simplexml

Recently the page checking code was breaking when used on a site. The XML returned from the supplier was being read using file_get_contents() and passed straight into simplexml_load_string() which was then kicking out a UTF-8 Encoding Error.

The way around this is to use utf8_encode() to ensure the string is encoded into UTF-8 before passing to simplexml_load_string(). In this instance my code goes like:

{code type=php}
$FileContents = file_get_contents( $URL ) ;
if ( $FileContents !== false )
{
   $xml  = simplexml_load_string( utf8_encode( $FileContents ) ) ;
}
{/code}

Leave a Reply

Your email address will not be published.