我想要獲取html div數據,其中id從特定名稱或字符串開始。從DOM中獲取從特定id名稱開始的div數據
例如,假設我有這個網站的數據: -
<html>
<div id="post_message_1">
somecontent1
</div>
<div id="post_message_2">
somecontent2
</div>
<div id="post_message_3">
somecontent3
</div>
</html>
爲此,我試過捲曲。
<?php
function file_get_contents_curl($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$html = file_get_contents_curl("myUrl");
$fh = fopen("test.html", 'w'); // we create the file, notice the 'w'. This is to be able to write to the file once.
//writing response in newly created file
fwrite($fh, $html); // here we write the data to the file.
fclose($fh);
?>
如果我使用
$select= $doc->getElementById("post_message_");
,則它不會返回數據,因爲其搜索這個ID在DOM,但在HTML DIV ID只能從該字符串開始。它可能是post_message_1或post_message_2。
嗨,感謝您的建議,但是當我使用xpath,然後我得到這個錯誤「PHP致命錯誤:未捕獲異常'異常'消息'字符串不能被解析爲XML'」,您可以瞭解HTML給,只是爲了演示的目的。 – neo
您的意思是說您無法將'file_get_contents_curl'的html輸出轉換爲php對象simplexmlElement?我的意思是,如果你可以利用'SimpleXMLElement',你可以非常容易地做任何你需要的工作 – smarber
是的,很多警告也顯示像「PHP Warning:SimpleXMLElement :: __ construct(): English<選項值=「78」class =「fjdpth2」> in /var/www/index.php on line 1「 – neo