我尝试获取外部网站的源代码来加载它们并使用此代码。我需要处理一些div的内容 - 由类或特定名称命名。
起初我以这种方式获得源代码
$url='http://www.example.com/site.html';
$page = file_get_contents($url);
现在我必须在$ page中搜索一些div,例如搜索name =“test1”或class =“test2”的div,同样我还要查找其他一些元素,比如特定的名称或类。
现在我可以使用str_replace,探索等来构建一个长期无用的方式来做到这一点 - 有人可以告诉我如何以简单快捷的方式做到这一点?也许我可以在一种数组或其他东西中加载源代码?
非常感谢
对我来说,只有file_get_contents有效 - file_get_html不会工作!?
一个非常快速的基本示例,说明如何使用DOMDocument
和DOMXPath
查找页面中的元素。您将需要阅读我怀疑DOMDocument
和DOMXPath
的手册,并且可能找到一个好的XPath
备忘单〜如this
$url='http://www.example.com/site.html';
$dom=new DOMDocument;
$dom->loadHTMLFile( $url );
$xp=new DOMXPath( $dom );
$query='//div[ contains( @class,"test" ) ]';
$col=$xp->query( $query );
if( $col && $col->length>0 ){
foreach($col as $node)echo $node->nodeValue;
}