simplexml_load_file()、simplexml_load_string()でparser error : Input is not proper UTF-8, indicate encoding !

simplexml_load_file()、simplexml_load_string()で次のようなエラーが出ることがあります。

Warning: simplexml_load_file() [function.simplexml-load-string]: Entity: line 4: parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0x8B 0x81 0x90 0x6C in xxxx line 00

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 4: parser error : Input is not proper UTF-8, indicate encoding ! Bytes: 0x8B 0x81 0x90 0x6C in xxxx line 00

この場合、取得するXMLの文字コードが間違っているか、XMLの中に不正な文字コードの文字が含まれています。

文字コードが間違っている場合は文字コードを変換します。 この場合、変換処理が必要なためsimplexml_load_file()は使えません。一旦file_get_contents()でデータを取得して、文字コード変換をしてsimplexml_load_string()に渡します。

$str = file_get_contents(【ファイルURL】);
$str = mb_convert_encoding($str,"UTF-8","SJIS-win");
$xml = simplexml_load_string($str);

文字コードがUTF-8かShift-JISか不確かな場合は、次のようにして両方に対応させることもできます。

$str = file_get_contents(【ファイルURL】);
if($xml = @simplexml_load_string($str)){
  $str = mb_convert_encoding($str,"UTF-8","SJIS-win");
  $xml = @simplexml_load_string($str);
}

ただしこの場合はUTF-8に含まれる文字コードの文字のみで構成されたShift-JISだと難しいです。
また『simplexml_load_stringでエラーが発生したらShift-JISとする』ということになるので、文字コード以外のエラーでもShift-JIS判断になります。

mb_detect_encodingを使用すると、文字コードを判断することができます。

$str = file_get_contents(【ファイルURL】);
$encode = mb_detect_encoding( strip_tags( $str ) );
$str = mb_convert_encoding( $str, $encode, "SJIS-win,EUCJP-win,UTF-8,JIS,ASCII");
$xml = simplexml_load_string($str);

ただstrip_tags()でタグを除いて、mb_detect_encoding()で文字コードの判定を行っていますが、mb_detect_encoding()は使用されている文字コード領域から文字コードを判断するのでstrip_tags()は不要かもしれません。
またmb_detect_encoding()は誤判断がされるようです。

たとえばShift-JISでよく使用される『 \x81 』はこれにもう1バイト加わって1文字のShift-JISになりますが、mb_detect_encoding()では『 \x81 』のみでShift-JISと判断してしまいます。

mb_detect_encoding("\x81", "SJIS")

関連記事

スポンサーリンク

RADIANS関数 度からラジアンに変換する

ホームページ製作・web系アプリ系の製作案件募集中です。

上に戻る