我只有一個用於HTML解析的PHP腳本,它適用於簡單的網站,但現在我需要解析this website的電影程序。我正在使用file_get_contents
函數,它只返回4個新的行分隔符\n
,我只是不明白爲什麼。 由於程序本身只是彈出式窗口,並且它似乎沒有更改URL地址,但我會在檢索HTML代碼後嘗試處理此問題,因此網站本身將更難以用DOMDocument解析XPath現場。PHP file_get_contents僅返回換行
這裏是我的腳本的縮短版:
<?php
$url = "http://www.cinemacity.cz/";
$content = file_get_contents($url);
$dom = new DomDocument;
$dom->loadHTML($content);
if ($dom == FALSE) {
echo "FAAAAIL\n";
}
$xpath = new DOMXPath($dom);
$tags = $xpath->query("/html");
foreach ($tags as $tag) {
var_dump(trim($tag->nodeValue));
}
?>
編輯:
因此,繼WBAR(謝謝)的建議,我一直在尋找一種方式如何改變標題中file_get_contents()函數這是我在其他地方找到的答案。現在我能夠獲得該網站的HTML,希望我將管理這個爛攤子解析:d
<?php
libxml_use_internal_errors(true);
// Create a stream
$opts = array(
'http'=>array(
'user_agent' => 'PHP libxml agent', //Wget 1.13.4
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$content = file_get_contents('http://www.cinemacity.cz/', false, $context);
$dom = new DomDocument;
$dom->loadHTML($content);
if ($dom == FALSE) {
echo "FAAAAIL\n";
}
$xpath = new DOMXPath($dom);
$tags = $xpath->query("/html");
foreach ($tags as $tag) {
var_dump(trim($tag->nodeValue));
}
?>
哎呀返回,他們的代碼確實是一個爛攤子。 html之間有很多新行。也許dom解析器被這個困惑了?我不知道。在將它提供給dom解析器之前,在多個換行符上嘗試使用replace_all? – 2012-10-07 11:50:10
如果您使用命令行的默認php config不允許外部URL獲取,請檢查! – xception