メインコンテンツに移動

メインナビゲーション

  • ホーム
  • サイトマップ
  • ビデオ
  • ご連絡

パンくず

  • ホーム
  • PHPのDOMDocumentで取り込んだhtml日本語を出力する際に文字化け

PHPのDOMDocumentで取り込んだhtml日本語を出力する際に文字化け

php
development
html

PHPのDOMDocumentで取り込んだ日本語htmlを出力するときに文字化けとなります

  • 作業環境:Windows10、Apache2.4、PHP5.6、html文字コードはUTF-8
  • DOMDocumentで日本語のhtmlコードを取り込んで、特定なタグ(例:h2)の内容を取得し、出力します
    $html_str = "<h2>テスト文言</h2>";          // テスト文字列
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML( $html_str );                // DOMDocumentに取り込む
    $h2 = $doc->getElementsByTagName('h2');     // h2タグエレメント取得
    echo $h2[0]->nodeValue;                     // 出力
  • 出力すると、文字化けになります

原因:DOMDocument::loadHTMLの初期エンコードはISO-8859-1になっています

  • 英文の場合に問題はないですが、日本語を取り込むときにUTF-8の文字コードを指定する必要があります( mb_convert_encoding)
    $html_str = "<h2>テスト文言</h2>";
    $doc = new DOMDocument();
    libxml_use_internal_errors(true);
    $doc->loadHTML( mb_convert_encoding($html_str, 'HTML-ENTITIES', 'UTF-8') );
    $h2 = $doc->getElementsByTagName('h2');
    echo $h2[0]->nodeValue;
  • 上記コードで出力すると文字化け問題は解消されます
ホーム

古松

検索

Article Category

  • apache(7)
  • css(19)
  • drupal(295)
  • Electron(4)
  • html(34)
  • javascript(27)
  • laravel(4)
  • linux(5)
  • macOS(2)
  • mysql(13)
  • php(19)
  • python(4)
  • SEO(12)
  • video(72)
  • Visual Studio Code(4)
  • windows(13)
  • wordpress(32)