Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
需要一个好的php HTML解析器吗_Html_Parsing - Fatal编程技术网

需要一个好的php HTML解析器吗

需要一个好的php HTML解析器吗,html,parsing,Html,Parsing,找到了这个,但它不起作用 extracting this page http://php.net/manual/en/function.curl-setopt.php and parse it to plain html, it failed and returned a partial html page 这就是我想做的, 转到html页面并获取各个组件(层次结构中所有div和p的内容) 我喜欢simplehtmldom的特性任何这样的解析器都是必需的,它在所有代码中都是优秀的(最好的和最差

找到了这个,但它不起作用

extracting this page http://php.net/manual/en/function.curl-setopt.php
and parse it to plain html, it failed and returned a partial html page
这就是我想做的, 转到html页面并获取各个组件(层次结构中所有div和p的内容) 我喜欢simplehtmldom的特性任何这样的解析器都是必需的,它在所有代码中都是优秀的(最好的和最差的)。

我经常使用它,在一般情况下,它的效果并不太差——我喜欢在文档作为DOM加载后使用


不幸的是,我认为,在某些情况下,如果HTML页面的格式真的很糟糕,可能会出现一些解析问题。。。从那时起,你开始明白尊重网络标准是一个好主意……

以帕斯卡·马丁的回应为基础

我使用CURL和XPATH的组合。下面是我在一个类中使用的函数

protected function _get_xpath($url) {
    $refferer='http://www.whatever.com/';
    $useragent='Googlebot/2.1 (http://www.googlebot.com/bot.html)';
    // create curl resource
    $ch = curl_init();

    // set url
    curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
    curl_setopt ($ch, CURLOPT_REFERER, $refferer);
    curl_setopt($ch, CURLOPT_URL, $url);

    //return the transfer as a string
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    // $output contains the output string
    $output = curl_exec($ch);
    //echo htmlentities($output);

    if(curl_errno($ch)) {
        echo 'Curl error: ' . curl_error($ch);
    }
    else {
        $dom = new DOMDocument();
        @$dom->loadHTML($output);
        $this->xpath = new DOMXPath($dom);
        $this->html = $output;
    }

    // close curl resource to free up system resources
    curl_close($ch);
}
然后,您可以使用解析文档结构并提取所需的信息

$resultDom = $this->xpath->evaluate("//span[@id='headerResults']/strong");
$this->results = $resultDom->item(0)->nodeValue;

我发现最适合我使用的是-

好吧,作为一个必须解析别人代码的人,尊重网络标准是完全不相干的,不是:-)@Johannes>的确;;但是,如果你试图解析别人的HTML,你也有可能在某一天产生HTML。。。而且,那天,记住解析糟糕的HTML时遇到的困难可能会鼓励您编写干净的HTML(满怀希望地…)