PHP DOMDocument でDOM操作

参考:PHPのDOMを使いやすくする <-これを採用(軽量で使いやすい)

NOTICE) ノードは単一ノード(内部は子孫OK)限定、並列的な複数ノードはNG

TODO) 配列に一致するクラスを取得し、何かをする(取得、置き換え、削除、何か)

テスト出力

//読み込み
include $_SERVER['DOCUMENT_ROOT'] . "/lib/document.php";
//単一ノードを指定
$document = new document('<div id="hoge"><div class="hdl-df item">なんでやねん</div><div class="hdl-df item">うそ??</div></div>');

//指定ノード内で探索
$defs = $document->querySelectorAll('.hdl-df');

//配列を回して処理
foreach($defs as $def){
  //クラスを削除して
 $def->removeAttribute('class');
 //新たなクラスを追加
 $def->setAttribute('class', 'hdl-df hdl-new');
}

//処理後に出力
print $document;




PHP Simple HTML DOM ParserでDOM操作(不採用:備忘録)

参考リンク:PHP Simple HTML DOM Parserでスクレイピング

本家マニュアル:PHP Simple HTML DOM Parser Manual

日本語解説サイト:PHP Simple HTML DOM Parser Manual

参考リンク:複数クラスの操作

参考リンク:出力方法とか

// PHP Simple HTML DOM Parser の読み込み
require_once 'simple_html_dom.php';

// HTMLファイルを読み込みオブジェクト化します
$html = str_get_html( '<html><body>Hello!</body></html>' );

// bodyタグを取得し、text部分を取り出します
print_r($html->find("body",0)->plaintext);


上記を活用して、変数内のhtmlをdom操作する

// PHP Simple HTML DOM Parser の読み込み
require_once "simple_html_dom.php";

$url = "http://www.metro.tokyo.jp/";

// URLを指定してオブジェクト化します
$html = file_get_html($url);

print_r($html->find("a",0)->plaintext);


$text=<<<EOF
<html>

<body>
<h1>サンプルサイト</h1>

<div id="SampleA">
サンプルサイトAの紹介
<div class="SampleBoxA"><a href="http://www.yahoo.com">Yahoo!</a></div>
<div class="SampleBoxA"><a href="http://www.google.com">Google</a></div>
</div><!--Sample-->

<div id="SampleB">
サンプルサイトBの紹介
<div class="SampleBoxB"><a href="http://www.example.com">Example</a></div>
<div class="SampleBoxB"><a href="http://www.google.com">Google</a></div>
</div><!--SampleB-->

</body>
</html>
EOF;

$html = str_get_html($text);

//表示
foreach($html->find('#SampleB a') as $element){
echo $element->href . '<br>';
}

//出力結果
http://www.example.com
http://www.google.com