【发布时间】:2018-12-21 12:02:00
【问题描述】:
我正在尝试使用 CURL DOMDocument 或 Xpath 解析 HTML,但 CURLOPT_RETURNTRANSFER 总是以字符串形式返回 url 的 HTML,这使得解析的 HTML 无效
返回的输出:
string(102736) "<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/QAPage" class="html__responsive">
<head>
<title>html - PHP outputting text WITHOUT echo/print? - Stack Overflow</title>
<link rel="shortcut icon" href="https://cdn.sstatic.net/Sites/stackoverflow/img/favicon.ico?v=4f32ecc8f43d">
<link rel="apple-touch-icon image_src" href="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon.png?v=c78bd457575a">
<link rel="search" type="application/opensearchdescription+xml" title="Stack Overflow" href="/opensearch.xml">
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0, minimum-scale=1.0">"
PHP 狙击查看输出
$cc = $http->get($url);
var_dump($cc);
使用的 CURL 库: https://github.com/seikan/HTTP/blob/master/class.HTTP.php
当我删除 CURLOPT_RETURNTRANSFER 时,我看到没有字符串 (102736) 的 HTML,但即使我没有请求它也会回显 url(参考:curl_exec printing results when I don't want to)
这是我用来解析 html 的 PHP 狙击:
$cc = $http->get($url);
$doc = new \DOMDocument();
$doc->loadHTML($cc);
// all links in document
$links = [];
$arr = $doc->getElementsByTagName("a"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
$href = $item->getAttribute("href");
$text = trim(preg_replace("/[\r\n]+/", " ", $item->nodeValue));
$links[] = [
'href' => $href,
'text' => $text
];
}
有什么想法吗?
【问题讨论】: