【问题标题】:How can I use PHP Simple HTML DOM to get the contents of a tags attribute?如何使用 PHP Simple HTML DOM 获取标签属性的内容?
【发布时间】:2012-08-03 14:09:52
【问题描述】:

我想获取<img> 标签的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
}

我做错了什么?

【问题讨论】:

  • 您在第一行缺少第一个'!!!
  • 我只是在删除不必要的代码时忽略了它。它实际上在我的代码中。我尝试按照简单 dom 的文档页面进行操作,但无法使其正常工作。但是,我能够获取各种标签的内容。我只是不能只捕获属性。
  • 哦,好吧,是否可以转储$str 的输出并检查它是否是所需的输出?
  • 我已经成功地做到了$tag = $html->find('h1',0);,所以问题一定出在上面的最后两行代码上。
  • 哦,太好了!但是有什么区别呢?两个都对呐?您在问题中使用了img 标签,现在在您的答案中使用了h1

标签: php simpledom


【解决方案1】:

试试这个:-

<?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>'; 
}
?>

【讨论】:

    【解决方案2】:

    您在第一行缺少第一个'!!!

    替换:

    require_once( simple_html_dom.php');
    

    与:

    require_once( 'simple_html_dom.php');
    

    【讨论】:

    • 再次检查第一行,不要遗漏第一行中的第一个 '。
    • @AbidHussain 我很早就给出了答案,并且 OP 回复说他已经更正了。我们正在讨论这个问题,并介意删除那个不赞成票,不管是谁投票的?很快就会更新答案!!!
    【解决方案3】:

    您可以使用 PHP 提供的 DOM 解析器来获取第一张图片的 src,如下所示:

    $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";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      相关资源
      最近更新 更多