作成日:2017-11-28, 更新日:2020-10-26
ライブラリの読込
ライブラリなので読み込む必要あり。
include_once('simple_html_dom.php');
データの読込:HTMLのソース取得
- HTMLを読み込むとき
-
$html = str_get_html('<html><b>aa</b></html>');
- URLからウェブページを読み込むとき
-
$html = file_get_html('http://tips.recatnap.info/');
「$html」をこのあと使うんだけど、途中で文字化けする可能性を考慮してutf8に変換してからのほうがいい。
データの読込:取得したHTMLから要素を取得
読み込んだデータから特定の何かを取り出す
<body>タグ内にある0番目の<b>タグの中身を抽出
※中身で別のタグが使われていたらそのまま抽出される。
- 記述パターン1
-
$gVal = $html->find('body b',0)->innertext;
- 記述パターン2
-
$gVaB = $html->find('body b'); $gVal = gVaB[0]->innertext;
<body>タグ内にある1番目の<b>タグを抽出(※中身だけではない)
$gVal = $html->find('body b',1)->outertext;
<body>タグ内にある0番目の<a>タグのhref属性の値を抽出
$gVal = $html->find('body a',0)->href;
<body>タグ内にある0番目の<a>タグのtitle属性の値を抽出
$gVal = $html->find('body a',0)->title;
関連項目
・Simple HTML DOM Parserの日本語訳
・php ShiftJisをUTF-8に変換(Simple HTML DOM Parser)
・php Simple HTML DOM Parserで属性で抜き出し
・Simple HTML DOM Parserのサンプル