如何使用 PHP 解析网页内的图像?
How parse images inside a web page with PHP?
我确定可能是重复的,但我对 "parsing web page with PHP" 有疑问。
我尝试推断网页内每个元素 <img>
的 src
、alt
和 title
,但出现此错误:
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;
}
我希望你能帮助我....非常感谢,对不起我的英语
find
returns 一个元素数组,因此您还需要遍历每个元素:
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;
}
}
我确定可能是重复的,但我对 "parsing web page with PHP" 有疑问。
我尝试推断网页内每个元素 <img>
的 src
、alt
和 title
,但出现此错误:
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;
}
我希望你能帮助我....非常感谢,对不起我的英语
find
returns 一个元素数组,因此您还需要遍历每个元素:
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;
}
}