2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PHPでHTMLをXML(SimpleXMLElement)に変換したい

Last updated at Posted at 2016-12-26

ちょっとはまったのでメモ

失敗例

ググったら出る方法。
これだと正しく変換できない。

badsample.php
<?php
$html = file_get_contents("/path/to/html/file.html");

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xml = simplexml_load_string($dom->saveHTML());

var_dump($xml); // Output: bool(false)

成功例

こうすればうまくいく。

goodsample.php
<?php
$html = file_get_contents("/path/to/html/file.html");

$dom = new DOMDocument();
@$dom->loadHTML($html);
$xml = simplexml_import_dom($dom);

var_dump($xml); // Output: SimpleXMLElements

所感

DOMDocumentをそのまま使えよっていうツッコミはなしの方向でお願いします

2
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?