DOMdocument和Xpath数组问题

时间:2018-11-06 02:27:33

标签: php laravel xpath domdocument

我在遇到关于file_get_contents和DOMdocument以及Xpath的麻烦。

我正在尝试刮擦。 因此,我为网站链接创建了一个数组。

array(9) {
  [0]=>
  string(34) "https://lions-mansion.jp/MF081014/"
  [1]=>
  string(34) "https://lions-mansion.jp/MF161026/"
  [2]=>
  string(34) "https://lions-mansion.jp/MF171045/"
  [3]=>
  string(34) "https://lions-mansion.jp/MF161016/"
  [4]=>
  string(34) "https://lions-mansion.jp/MF171010/"    
}

尝试使用foreach进入这些链接。并尝试抓取链接rel的href!

foreach ($siteUrls as $sites){
        @$html [] = file_get_contents($sites);
}



foreach ($html as $geturl)
{
    $grabber = new \DOMXPath($geturl);
    $mainLink [] = $grabber->query("//link[@rel='canonical']/@href");

}
    var_dump($mainLink);

但是最后还是遇到这个错误。

  

传递给DOMXPath :: __ construct()的参数1必须是的实例   DOMDocument,给定字符串

任何想法如何解决此问题?我如何获得该link rel url?从头标签

1 个答案:

答案 0 :(得分:2)

libxml_use_internal_errors:禁用libxml错误,并允许用户根据需要获取错误信息http://php.net/manual/en/function.libxml-use-internal-errors.php

<?php

$siteUrls = [
    "https://lions-mansion.jp/MF081014/",
    "https://lions-mansion.jp/MF161026/",
    "https://lions-mansion.jp/MF171045/",
    "https://lions-mansion.jp/MF161016/",
    "https://lions-mansion.jp/MF161016/"
];

foreach ($siteUrls as $sites){
    @$html [] = file_get_contents($sites);
}


libxml_use_internal_errors(true);

foreach ($html as $geturl)
{
    $dom = new DOMDocument();
    $dom->loadHTML($geturl);
    $grabber = new DOMXPath($dom);
    $names = $grabber->query("//link[@rel='canonical']/@href");
    foreach($names as $contextNode) {
        $mainLink[] = $contextNode->value;
    }
}
libxml_clear_errors();
var_dump($mainLink);


array (size=2)
  0 => string 'https://lions-mansion.jp/MF161026/' (length=34)
  1 => string 'https://lions-mansion.jp/MF171045/' (length=34)