我想要获取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