0

我正在尝试使用 curl 和 DOMDocument 提取信息,我必须提取所有链接的 div 层。

但没有向我展示任何东西,我不明白,因为如果它没有 curl 的话。

  function media_uri_request($url, $method='', $vars='') 
  {
        $ch = curl_init();
        if ($method == 'post') 
        {
        curl_setopt ($ch, CURLOPT_POST, 1);
        curl_setopt ($ch, CURLOPT_POSTFIELDS, $vars);
        }

        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, false);
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt ($ch, CURLOPT_FAILONERROR, false);
        curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.7.12) Gecko/20050915 Firefox/1.0.7");
        curl_setopt ($ch, CURLOPT_HTTPHEADER, array("REMOTE_ADDR: ".$_SERVER['REMOTE_ADDR'], "HTTP_X_FORWARDED_FOR: ".$_SERVER['REMOTE_ADDR']));
        curl_setopt ($ch, CURLOPT_COOKIEJAR, 'tmp/cookie.txt');
        curl_setopt ($ch, CURLOPT_COOKIEFILE, 'tmp/cookie.txt');
        curl_setopt ($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt ($ch, CURLOPT_TIMEOUT, 0);
        curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 0);
        $buffer = curl_exec($ch);
        curl_close ($ch);

        if (isset($buffer) && filter_var($buffer, FILTER_SANITIZE_URL)) {
        $urls = Array();

        $dom = new DOMDocument();
        @$dom->loadHTMLFile($buffer);

        foreach($dom->getElementsByTagName('a') as $buffer) {
            $urls[] = Array(
                'name'  => $buffer->nodeValue,
                'href'  => $buffer->getAttribute('href'),
                'title' => $buffer->getAttribute('title'),
                'rel'   => $buffer->getAttribute('rel'),
                'id'    => $buffer->getAttribute('id'),
            );
        }
        return $urls;
    }
  }

目前向我显示页面上的所有链接,但我只需要一个 div 的 id 并获取此链接。

<div id="something">
<a href="anylink">sometitle</a>
<a href="anylink">sometitle</a>
<a href="anylink">sometitle</a>
<a href="anylink">sometitle</a>
</div>

你能帮我吗?

4

1 回答 1

2

代替

foreach($dom->getElementsByTagName('a') as $buffer) {

foreach($dom->getElementById('something')->getElementsByTagName('a') as $buffer) {

这样做,您首先通过 id 找到 div,然后在其子项中搜索链接。阅读 DOMDocument:: getElementById () 了解更多信息。

有一种不同的方式:

$xpath = new DOMXPath($dom);
$elements = $xpath->query("//*[@id=something]");
if ($elements->length > 0) {
    foreach ($elements->item(0)->getElementsByTagName('a') as $buffer) {

此外,使用@$dom->loadHTML($buffer);- 从字符串加载 HTML,而不是从文件加载。

于 2012-10-03T22:59:01.643 回答