htmlSQL の最近のブログ記事
指定したURLのHTMLソースから目的のタグ内の文字列をSQL文で取り出すことができるライブラリを見つけました。
今までは正規表現を使って文字列を取得していましたが、このライブラリならタグはもちろん、idやclassまで検索対象にできるスグレモノで、SQLの文法と配列が理解できれば、いろいろなことに使えそうです。
このように「HTML内を部分的に取り出し、表示する」ことを「Webスクレイピング」というそうです。
使用準備
- ライブラリをダウンロードして任意のディレクトにアップロード。
- 利用するファイルに「snoopy.class.php」と「htmlsql.class.php」をインクルード。
使用例
<?php
include_once($_SERVER['DOCUMENT_ROOT']."/lib/snoopy.class.php");
include_once($_SERVER['DOCUMENT_ROOT']."/lib/htmlsql.class.php");
function getTitle($url){
$wsql = new htmlsql();
// connect to a URL
if (!$wsql->connect('url', $url )){
print 'Error while connecting: ' . $wsql->error;
exit;
}
// execute a query:
if (!$wsql->query('SELECT * FROM title')){
print "Query error: " . $wsql->error;
exit;
}
// show results:
foreach($wsql->fetch_array() as $row){
//print_r($row);
echo $row['text'];
}
}
getTitle("http://hoshiya.biz");
?>
ちなみに、print_r($row)とすると、$rowに格納されている配列の内容が確認できます。
$rowの中身→ Array ( [tagname] => title [text] => 星屋工作室 )
例文
その他の例文はまた今度...。
制限
<div>の中の<div>など、同じタグに囲まれている文字列や要素はダイレクトに取得できず、一度大枠を取得して、再度その中から抜き出さなければならないようです。
関連記事
-
Warning: Missing argument 2 for getTitleLink(), called in /home/sites/heteml/users158/m/h/0/mh0723/web/hoshiya.biz/blog/web/php/htmlsql/index.php on line 120 and defined in /home/sites/heteml/users158/m/h/0/mh0723/web/hoshiya.biz/include/function/function.php on line 104
PHP Simple HTML DOM Parserでタイトルタグ内の文字列を取得する:PHP|星屋工作室 hoshiya.biz -
Warning: Missing argument 2 for getTitleLink(), called in /home/sites/heteml/users158/m/h/0/mh0723/web/hoshiya.biz/blog/web/php/htmlsql/index.php on line 123 and defined in /home/sites/heteml/users158/m/h/0/mh0723/web/hoshiya.biz/include/function/function.php on line 104
ページタイトル(titleタグ内の文字列)を取得する:PHP,Javascript|星屋工作室 hoshiya.biz
トラックバック(0)
トラックバックURL:




