【问题标题】:How parse images inside a web page with PHP?如何使用 PHP 解析网页内的图像?
【发布时间】:2020-07-31 14:16:55
【问题描述】:

我确定可能是重复的,但我遇到了“使用 PHP 解析网页”的问题。 我尝试推断网页内每个元素<img>srcalttitle,但我有这个错误:

Uncaught Error: Call to a member function getElementsByTagName() on array in /web/example.php:12 Stack trace: #0 {main} thrown in 

为此,我创建了这个小代码:

include('../simple_html_dom.php');
$doc = file_get_html('https://www.example.com');

foreach($doc-> find('div.content')-> getElementsByTagName('img') as $item){
    $src =  $item->getAttribute('src');
    $title= $item->getAttribute('title');
    $alt= $item->getAttribute('alt');

    echo "\n";
    echo $src;
    echo $title;
    echo $alt;
}

我希望你能帮助我....非常感谢,对不起我的英语

【问题讨论】:

    标签: php parsing dom html-parsing simple-html-dom


    【解决方案1】:

    find 返回一个元素数组,因此您还需要遍历每个元素:

    foreach($doc->find('div.content') as $div) {
        foreach ($div->getElementsByTagName('img') as $item){
            $src =  $item->getAttribute('src');
            $title= $item->getAttribute('title');
            $alt= $item->getAttribute('alt');
    
            echo "\n";
            echo $src;
            echo $title;
            echo $alt;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 1970-01-01
      • 2011-03-14
      • 1970-01-01
      • 2015-09-17
      • 2013-11-24
      • 1970-01-01
      • 1970-01-01
      • 2022-08-02
      相关资源
      最近更新 更多