0

この次のコードを使用して、サイトのコンテンツを取得しています

function get_content($url){
    $content = @file_get_contents($url);
    if( empty($content) ){
      $content = get_url_contents($url);
    }
    return $content;
}

function get_url_contents($url){
    $crl = curl_init();
    $timeout = 90;
    curl_setopt ($crl, CURLOPT_URL,$url);
    curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
    $ret = curl_exec($crl);
    curl_close($crl);
    return $ret;
}

$url = "http://www.site.com";
$html = get_content($url);
echo $html;

すべて問題ありませんが、たとえば、すべての div 要素、ページのタイトル、またはすべての画像を取得する必要があります。

どうやってやるの?

ありがとう

4

2 に答える 2

5

HTML 解析ライブラリを使用します。それらの多くは存在しますが、私は個人的にSimpleHTMLDomを使用しており、良い経験をしています. JQuery スタイルのセレクターを使用しているため、習得が容易です。

いくつかのコード サンプル:

ページのタイトルを取得するには:

$html = str_get_html($html);
$title = $html->find('title',0);
echo $title->plaintext;

すべての div 要素の場合:

$html = str_get_html($html);
$divs = $html->find('div');

foreach($divs as $div) {
   // do something;
}
于 2012-08-24T05:18:27.493 に答える
1

DOMDocumentを使用できます

例えば:

$dom = new DOMDocument;
$dom->loadHTML($html);
$divs = $dom->getElementsByTagName('div');
foreach ($divs as $div) {
    echo $div->nodeValue. PHP_EOL;
}
于 2012-08-24T05:23:24.933 に答える