如何使用PHP简单HTML DOM获取标记属性的内容?
我想获取如何使用PHP简单HTML DOM获取标记属性的内容?,php,simpledom,Php,Simpledom,我想获取标记的src属性的内容。以下是我正在使用的代码: 我做错了什么?你在第一行缺少了第一个“!”!!! 替换: require_once( 'simple_html_dom.php'); $curl = curl_init(); curl_setopt($curl, CURLOPT_URL, $webpage); curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($curl, CURLOPT_CONNECTTIM
标记的src
属性的内容。以下是我正在使用的代码:
我做错了什么?你在第一行缺少了第一个
“
!”!!!
替换:
require_once( 'simple_html_dom.php');
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $webpage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$str = curl_exec($curl);
curl_close($curl);
if( $str )
{
$html= str_get_html($str);
$img = $html->find('img', 0); // get the first image on the page
$src = $img->src; // get the contents of the img src - but it doesn't seem to work
}
与:
您可以使用PHP提供的DOM解析器获得第一个图像的src,如下所示:
require_once( 'simple_html_dom.php');
试试这个:-
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $webpage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$html = curl_exec($curl);
curl_close($curl);
if( !empty($html) ) {
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($html);
#echo $doc->saveHTML();
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)");
echo "src=" . $src . "\n";
}
第一行缺少第一个“
!”!!!我只是在删除不必要的代码时忽略了它。它实际上在我的代码中。我试着按照简单dom的文档页面进行操作,但是我无法让它工作。然而,我能够得到各种标签的内容。我只是不能只捕获属性。哦,好的,可以转储$str
的输出并检查它是否是所需的输出吗?我已经成功地执行了$tag=$html->find('h1',0)代码>所以问题一定出在上面的最后两行代码上。哦,那太好了!但是有什么不同呢?两个都对吗?你在问题中使用了img
标记,现在在回答中使用了h1
。再次检查第一行,不要遗漏第一行中的第一个。@AbidHussain我很长时间地回覆了答案,OP回复说他已经更正了。我们正在讨论这个问题,介意取消否决票吗,是谁投的票?将很快更新答案!!!
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $webpage);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
$html = curl_exec($curl);
curl_close($curl);
if( !empty($html) ) {
$doc = new DOMDocument;
libxml_use_internal_errors(true);
$doc->loadHTML($html);
#echo $doc->saveHTML();
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)");
echo "src=" . $src . "\n";
}
<?php
include("simple_html_dom.php");
$webpage ="http://www.santabanta.com";
$html = file_get_html($webpage);
foreach($html->find('img') as $element) {
echo $element->src . '<br>';
}
?>