使用PHP Simple HTML DOM Parser下载图片报错求助
解决PHP Simple HTML DOM Parser下载图片时的file_get_contents/file_put_contents警告问题
Hey there, let's break down why those warnings are showing up and fix them step by step.
你遇到的警告信息
Warning: file_get_contents(): Filename cannot be empty in D:\xampp\htdocs\cra\index.php on line 11 Warning: file_put_contents(hinh/): failed to open stream: No such file or directory in D:\xampp\htdocs\cra\index.php on line 11
问题根源分析
These errors happen for a few key reasons:
- Empty image source: Some
<img>tags on the target page have an emptysrcattribute. When you try to pass this empty string tofile_get_contents(), it throws the "Filename cannot be empty" warning. - Invalid file path: When
$s(the image src) is empty,basename($s)returns an empty string. This makes$img_nameequal tohinh/, andfile_put_contents()tries to write to a directory instead of a file—hence the "failed to open stream" error. - Unresolved relative paths: Another hidden issue is that many image
srcvalues are relative paths (like/images/photo.jpgorassets/img.png), whichfile_get_contents()can't access directly since it doesn't know the base URL of the target site.
修复后的完整代码
PHP 处理逻辑
<?php include('simple_html_dom.php'); if(isset($_POST['submit'])){ // 验证并处理输入的URL $target_url = trim($_POST['url']); if(empty($target_url)){ echo "<p>请输入有效的目标网址!</p>"; exit; } // 自动补全HTTP/HTTPS前缀 if(!preg_match('/^https?:\/\//i', $target_url)){ $target_url = 'https://' . $target_url; } // 尝试加载目标页面 $url = file_get_html($target_url); if(!$url){ echo "<p>无法访问目标URL,请检查链接是否正确!</p>"; exit; } $images = $url->find("img"); foreach($images as $img){ $img_src = trim($img->src); // 跳过空的图片链接 if(empty($img_src)){ continue; } // 将相对路径转换为绝对URL $absolute_img_url = $img_src; if(!preg_match('/^https?:\/\//i', $absolute_img_url)){ $parsed_target = parse_url($target_url); $base_url = $parsed_target['scheme'] . '://' . $parsed_target['host']; // 处理根相对路径(以/开头) if(substr($absolute_img_url, 0, 1) == '/'){ $absolute_img_url = $base_url . $absolute_img_url; } else { // 处理相对路径(不以/开头) $absolute_img_url = $base_url . '/' . $absolute_img_url; } } // 确保文件名有效,避免空文件名 $img_basename = basename($absolute_img_url); if(empty($img_basename)){ // 生成随机文件名作为 fallback $img_basename = uniqid() . '.jpg'; } $img_name = 'hinh/' . $img_basename; // 尝试下载并保存图片,捕获错误 try { $img_content = file_get_contents($absolute_img_url); if($img_content !== false){ file_put_contents($img_name, $img_content); echo "<p>✅ 成功保存图片:$img_name</p>"; } else { echo "<p>❌ 无法下载图片:$absolute_img_url</p>"; } } catch (Exception $e) { echo "<p>❌ 下载图片出错:$absolute_img_url,错误信息:" . $e->getMessage() . "</p>"; } } } ?>
表单代码(优化版)
<form id="form1" name="form1" method="post" action="index.php"> <table width="700" border="1" align="center" cellpadding="1" cellspacing="1"> <tr> <td colspan="2"> <label for="textfield"></label> <input style="width:100%;" type="text" name="url" id="textfield" placeholder="请输入目标网址,例如:https://example.com" /> </td> </tr> <tr> <td colspan="2" align="center" valign="middle"> <input type="submit" name="submit" id="button" value="开始下载图片" /> </td> </tr> </table> </form>
关键修复点说明
- URL 验证与补全:先检查用户输入的URL是否为空,自动添加
https://前缀,避免无效的URL请求。 - 跳过空图片源:直接跳过
src为空的<img>标签,避免传递空值给文件操作函数。 - 相对路径转绝对路径:将目标页面中的相对路径图片链接转换为完整的绝对URL,确保
file_get_contents()能正确访问图片资源。 - 有效文件名处理:如果
basename()返回空(比如动态图片链接),生成随机文件名,避免file_put_contents()尝试写入目录。 - 错误捕获与提示:使用
try-catch捕获异常,并检查file_get_contents()的返回值,输出清晰的成功/失败提示,替代生硬的警告信息。
内容的提问来源于stack exchange,提问作者Sae
相关产品推荐
相关产品推荐

