LoginSignup
1
0

More than 1 year has passed since last update.

FuelPHP の Format でどうしても HTML のパースが失敗する場合

Posted at

備忘録

FuelPHP の HTML パーサー「Format」

FuelPHP で HTML をパースする時は、Format というライブラリを使います。使い方は以下です。

$html = \Format::forge($html_body, "xml")->to_array();
$element = $html["path"][2]["html"]["element"];

でも、これでも失敗する場合があります。それは例えば、以下のような 文字列とタグを一緒にしたタグをパースする場合です。

<dblp>
<inproceedings key="conf/aaim/He07" mdate="2007-06-28">
<author>Dan He</author>
<title>
<i>BMA</i>
<sup>*</sup>
: An Efficient Algorithm for the One-to-Some Shortest Path Problem on Road Maps.
</title>
<pages>346-357</pages>
<year>2007</year>
<crossref>conf/aaim/2007</crossref>
<booktitle>AAIM</booktitle>
<ee>http://dx.doi.org/10.1007/978-3-540-72870-2_33</ee>
<url>db/conf/aaim/aaim2007.html#He07</url>
</inproceedings>
</dblp>

Title タグの中に、文字列とタグが一緒になっていますね。
このようなタグなどだと、Format は上手くパースしてくれません。

このような場合はどうするのでしょうか?

Format の代わりに simplexml_load_string を使う

FuelPHP の HTML のパースは、simplexml_load_string というPHP組み込みの関数を使っています(該当コードはここ)。
そして、自分の場合、パースが失敗するのは、この simplexml_load_string を出力する際に上手く結果が表示されないからでした。


なのでここではこの simplexml_load_string を使ってパースして、その結果を dom_import_simplexml という組み込みの関数で取得します。

$body_xml = simplexml_load_string($html_body);
$unseen_xml = dom_import_simplexml($array_body2_xml->path->to-unseen->element);
echo $unseen_xml->textContent;

これで、Format で見えなかった要素も見れるようになれます。
(理想的には、Format::forge の結果から dom_import_simplexml したいのですが、コードだと SimpleXMLELement から array にしているので上手くいきませんでした)

を参考にしました。

1
0
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
1
0