Curl For循环只读取数组的最后一个元素


Curl For Loop Reading Only Last Element Of Array

下面是我使用的代码。

它从文本区读取链接,然后获取源代码,最后过滤元标签。但是,它只显示数组中的最后一个元素。

因此,如果我在文本区域中放入3个网站,它只会读取最后一个,其他的只是显示为空白。

我已经试了几个小时了,请帮忙。

function file_get_contents_curl($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}
if(isset($_POST['url'])){
    $url = $_POST['url'];
    $url = explode("'n",$url);
    print_r($url);
    for($counter = 0; $counter < count($url); $counter++){
        $html = file_get_contents_curl($url[$counter]); // PASSING LAST VALUE OF ARRAY
        $doc = new DOMDocument();
        @$doc->loadHTML($html);
        $nodes = $doc->getElementsByTagName('title');
        $title = $nodes->item(0)->nodeValue;
        $metas = $doc->getElementsByTagName('meta');
        for ($i = 0; $i < $metas->length; $i++){
            $meta = $metas->item($i);
            if($meta->getAttribute('name') == 'description')
                $description = $meta->getAttribute('content');
            if($meta->getAttribute('name') == 'keywords')
                $keywords = $meta->getAttribute('content');
        }
        print
        ('
        <fieldset>
            <table>
                <legend><b>URL: </b>'.$url[$counter].'</legend>
                <tr>
                    <td><b>Title:</b></td><td>'.$title.'</td>
                </tr>
                <tr>
                    <td><b>Description:</b></td><td>'.$description.'</td>
                </tr>
                <tr>
                    <td><b>Keywords:</b></td><td>'.$keywords.'</td>
                </tr>
            </table>
        </fieldset><br />
        ');
    }
}                            

这是一个令人讨厌的小错误-但这里是(荒谬的简单)解决方案:

你的URL被添加了空白,除了最后一个URL,所以你需要修剪它,你可以这样做:

curl_setopt($ch, CURLOPT_URL, trim($url));

如果可用,您可能只使用file_get_contents()(仍然需要您修剪URL)。

第二个问题是,如果没有meta数据,那么旧的变量被使用(从以前的循环),所以就在你的主循环结束之前,在你的print()添加以下内容:

unset($title,$description,$keywords);