我不解析此網址:http://foldmunka.netDOMDocument類無法訪問れ
$ch = curl_init("http://foldmunka.net");
//curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); //not necessary unless the file redirects (like the PHP example we're using here)
$data = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
clearstatcache();
if ($data === false) {
echo 'cURL failed';
exit;
}
$dom = new DOMDocument();
$data = mb_convert_encoding($data, 'HTML-ENTITIES', "utf-8");
$data = preg_replace('/<\!\-\-\[if(.*)\]>/', '', $data);
$data = str_replace('<![endif]-->', '', $data);
$data = str_replace('<!--', '', $data);
$data = str_replace('-->', '', $data);
$data = preg_replace('@<script[^>]*?>.*?</script>@si', '', $data);
$data = preg_replace('@<style[^>]*?>.*?</style>@si', '', $data);
$data = mb_convert_encoding($data, 'HTML-ENTITIES', "utf-8");
@$dom->loadHTML($data);
$els = $dom->getElementsByTagName('*');
foreach($els as $el){
print $el->nodeName." | ".$el->getAttribute('content')."<hr />";
if($el->getAttribute('title'))$el->nodeValue = $el->getAttribute('title')." ".$el->nodeValue;
if($el->getAttribute('alt'))$el->nodeValue = $el->getAttribute('alt')." ".$el->nodeValue;
print $el->nodeName." | ".$el->nodeValue."<hr />";
}
我需要順序中高音,所有權屬性和簡單的文字,但這個頁面我不能在body標籤中訪問節點。
如果有人知道如何用xpath查詢過濾出cdata-section,請對其進行評論。 – 2010-11-20 00:18:46
@styu我看着你的要求,但我不明白OP的問題。您可以嘗試將'LIBXML_NOCDATA'選項傳遞給'load'調用。由於抓取的頁面是有效的XHTML,因此您可能還想使用XML解析器而不是HTML解析器。 – Gordon 2010-11-20 09:53:03
@Gordon:turbod澄清在[佩卡的回答(http://stackoverflow.com/questions/2735291/domdocument-class-unable-access-domnode/2735318#2735318),他希望使網站的純文字版,包括'a'和'img'標籤的'title'和'alt'屬性。正如我所看到的那樣,使用'load()'它不像預期的那樣工作,但我不知道爲什麼(在這種情況下它不提取屬性)。 – 2010-11-20 14:08:59