无法获取包含file_get_contents的网页内容



尝试使用file_get_contents

获取页面内容

页面:http://www.sapporo-keihan.jp/maruyama/outline

function pageContent(String $url): DOMDocument
    {
       $html = cache()->rememberForever($url, function () use ($url) {
           $opts = [
               "http" => [
                   "method" => "GET",
                   "header" => "Accept: text/htmlrn"
               ]
           ];
           $context = stream_context_create($opts);
           $file = file_get_contents($url, false, $context);
           return $file;
       });
       $parser = new DOMDocument();
       libxml_use_internal_errors(true);
       $parser->loadHTML($html = mb_convert_encoding($html,'HTML-ENTITIES', 'ASCII, JIS, UTF-8, EUC-JP, SJIS'));
       return $parser;
    }

    $html = pageContent("http://www.sapporo-keihan.jp/maruyama/outline");
    $path = new DOMXPath($html);
    $catch = $path->query("//body");
    foreach ($catch as $found){
        $site = trim($found->nodeValue);
    }

,但我无法正确返回内容。而不是内容,而是给我页面的CSS。功能有什么问题。是什么原因导致了这个问题。谢谢!

似乎对于此URL,服务器默认情况下返回CSS。指定HTTP Accept: text/html标头进行修复。

您可以按照以下方式进行操作:

$opts = [
  "http" => [
    "method" => "GET",
    "header" => "Accept: text/htmlrn"
  ]
];
$context = stream_context_create($opts);
$file = file_get_contents($url, false, $context);

最新更新