0

ワードプレスに移行できるように、クライアントのサイトのホームページのすべての URL をスクレイピングしようとしています。問題は、重複除去された URL のリストに到達できないように見えることです。

コードは次のとおりです。

$html = file_get_contents('http://www.catwalkyourself.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
   $href = $hrefs->item($i);
   $url = $href->getAttribute('href');

   if($url = preg_match_all('((www|http://)(www)?.catwalkyourself.com\/?.*)', $url, $matches[0])){
    $urls = $matches[0][0][0];
    $list = implode( ', ', array_unique( explode(", ", $urls) ) );
    echo $list . '<br/>';
    //print_r($list);
   }
}

(こちらにも掲載しています。)

代わりに、次のような重複が発生しています。

http://www.catwalkyourself.com/rss.php
http://www.catwalkyourself.com/rss.php

これを修正するにはどうすればよいですか?

4

2 に答える 2

3

コードが現在ループで構造化されている方法では、常にarray_unique配列サイズ 1 で呼び出しています。

URL のリストを作成してから、array_unique を呼び出す必要があります。これを試して:

<?php

$html = file_get_contents('http://www.catwalkyourself.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
$urls  = array();

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url  = $href->getAttribute('href');

    if( ($count = preg_match_all('((www|http://)(www)?.catwalkyourself.com\/?.*)', $url, $matches[0])) > 0) {
        $urls[] = $matches[0][0][0]; // build list of URLs in the loop
    }
}

$list = implode( ', ', array_unique( $urls ) );
echo $list . '<br/>';
于 2012-06-22T18:15:03.217 に答える
1

コードの最後の部分はループに入れないでください。ページ上のすべてのリンクを含む配列をトラバースしています。この配列の各要素にはリンクが 1 つしか含まれてarray_uniqueいないため、複数の要素を含むことができない配列に適用しています。

次のようなことを試してください:

$html = file_get_contents('http://www.catwalkyourself.com');

$dom = new DOMDocument();
@$dom->loadHTML($html);

// grab all the on the page
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");
$urls = array();

for ($i = 0; $i < $hrefs->length; $i++) {
    $href = $hrefs->item($i);
    $url = $href->getAttribute('href');

    if($url = preg_match_all('((www|http://)(www)?.catwalkyourself.com\/?.*)', $url, $matches[0])){
        $urls[] = $matches[0][0][0];
    }
}
$list = implode(', ', array_unique($urls));
echo $list . '<br/>';
于 2012-06-22T18:17:41.533 に答える