ホームページ  >  記事  >  バックエンド開発  >  simple_html_dom_PHP チュートリアルに基づく使用法の概要

simple_html_dom_PHP チュートリアルに基づく使用法の概要

WBOY
WBOYオリジナル
2016-07-21 15:01:50946ブラウズ

コードをコピーします コードは次のとおりです:

简单范例
$html = file_get_html('http://www.google.com/'); //获取html$dom = new simple_html_dom(); //new simple_html_dom对象$dom->load($html)      //加载html// Find all images foreach($dom->find('img') as $element) {   //获取img标签数组       echo $element->src . '
';    //获取每个img标签中的src}// Find all links foreach($dom->find('a') as $element){    //获取a标签的数组       echo $element->href . '
';    //获取每个a标签中的href}


$html = file_get_html('http://slashdot.org/');   //获取html$dom = new simple_html_dom();    //new simple_html_dom对象$dom->load($html);     //加载html// Find all article blocksforeach($dom->find('div.article') as $article) {       $item['title']     = $article->find('div.title', 0)->plaintext; //plaintext 获取纯文本    $item['intro']    = $article->find('div.intro', 0)->plaintext;    $item['details'] = $article->find('div.details', 0)->plaintext;    $articles[] = $item;}print_r($articles);

}


// Create DOM from string

$html = str_get_html('

Hello
World
');
$dom = new simple_html_dom();     //new simple_html_dom对象

$dom->load($html);      //加载html
$dom->find('div', 1)->class = 'bar';    //class = 赋值 给第二个div的class赋值

$dom->find('div[id=hello]', 0)->innertext = 'foo';   //innertext内部文本

echo $dom;

// Output:

foo
World

DOM メソッドとプロパティ
名前 説明
void __construct ([string $filename]) コンストラクター、ファイル名パラメーターは、内容に関係なく自動的にロードされます。テキストまたはファイル/URL。
string plaintext プレーンテキスト
void clear () メモリのクリア
voidload (string $content ) コンテンツのロード
string save ( [string $filename] ) $filename が設定されている場合は、結果を文字列にダンプします。 string はファイルに保存されます。
voidload_file ( string $filename ) ファイルまたは URL からコンテンツを読み込みます。
void set_callback ( string $function_name ) コールバック関数を設定します。
mixed find ( string $selector [, int $index] ) は、要素の CSS セレクターを検索します。インデックスが設定されている場合は n 番目の要素オブジェクトを返し、それ以外の場合は配列オブジェクトを返します。


4. find メソッドの詳細な紹介


find ( string $selector [, int $index] )
// すべてのアンカーを検索し、要素の配列を返しますオブジェクト タグ配列
$ret = $html->find('a');

// (N) 番目のアンカーを検索し、要素オブジェクトを返すか、見つからない場合は null を返します (ゼロベース)最初のタグ
$ret = $html->find('a', 0);

// 最新のアンカーを検索し、要素オブジェクトを返すか、見つからない場合は null を返します (ゼロベース)最後のタグ
$ret = $html->find('a', -1);

// id 属性を持つすべての

を検索します
$ret = $html - >find('div[id]');

// 属性 id=foo
$ret = $html->find('div[id = foo]');


// id=foo
$ret = $html->find('#foo');

$ret = $html->find('.foo');

// 属性 id を持つすべての要素を検索
$ret = $html - >find('*[id]');

// タグと img タグの配列からすべてのアンカーと画像を検索します
$ret = $html->find('a, img ' );

// 「title」属性を持つすべてのアンカーと画像を検索します
$ret = $html->find('a[title], img[title]');< ; /P>


//