php - 如何使用 PHP 解析网页内的图像?
问题描述
我确定可能是重复的,但我遇到了“使用 PHP 解析网页”的问题。我尝试推断src
,alt
和网页内title
的每个元素,但我有这个错误:<img>
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
返回一个元素数组,因此您还需要遍历每个元素:
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;
}
}
推荐阅读
- python - 所有列的 2 列之间的相关性
- reactjs - 为什么我更新安全规则后无法将数据写入 Firebase
- c++ - 为什么 sorted_vector_map 中的 [] 运算符?
- python - OpenCV Jigsaw Puzzle 获得“干净”的轮廓
- python - PDF 文档不包含 utf-8 编码
- javascript - 从嵌套访问包含唯一数据集属性的特定元素s
- security - pdfbox - 如何以增量方式签署更新的文档或更改
- python - 如何在公会中获取每个成员的ID
- reactjs - 有没有办法在 React 的函数中调用你的主要组件?
- javascript - 我在 vue js 的样式标签中加载背景图像时遇到问题