/ / DOMDocumentによるPHPエンコーディング-php、dom、character-encoding

DOMDocumentによるPHPエンコーディング - PHP、DOM、文字エンコーディング

<tag>
Алекс М
</tag>

DOMDocument関数を使用して次のコードのコンテンツを取得しようとすると、次のような結果が返されます。

ÐÐ»ÐµÐºÑ Ðœ

mb_convert_encoding、iconv、utf8_encodeを使用してDOMDocumentエンコーディングを異なる値(utf-8、ISO-8859-1)に設定しようとしましたが、成功しませんでした。

「ÐлекÑÐœ」の代わりに「АлексМ」を取得するにはどうすればよいですか?

編集:入力はcurlでロードされたページから来ています。ページコンテンツをブラウザに出力すると、文字が正しく表示されます(したがって、入力が問題であるとは思わない)。

回答:

回答№1は42

試してください:

$string = file_get_contents("your-xml-file.xml");
$string = mb_convert_encoding($string, "utf-8", mb_detect_encoding($string));
// if you have not escaped entities use
$string = mb_convert_encoding($string, "html-entities", "utf-8");
$doc = new DOMDocument();
$doc->loadXML($string);

回答№2の19

XPathを使用してDomDocumentを解析し、これを読んだ後、同様の問題が発生しました

https://bugs.php.net/bug.php?id=32547

このように解決しました

// Workaround because PHP 5.2.x has encoding problems, when we
// update to PHP 5.3 this line is not necesserry any more
$content = "<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />" . $content;

// Creating new DOM document and loading HTML content
$dom_document = new DOMDocument("1.0", "utf-8");
$dom_document->substituteEntities = TRUE;
$dom_document->loadHTML($content);

回答№3の6

タグにxmlヘッダーを追加-これを試してください:

$a = new DOMDocument ();
$a->loadXml ("<?xml version="1.0" encoding="utf-8"?><tag>Алекс М</tag>");
print htmlspecialchars ($a->saveXml ());