缺少来自外部Url php的照片

时间:2012-01-04 08:36:41

标签: php html dom

我正在使用服务器端从外部网址获取照片。我正在使用简单的php dom库来获取这个建议。但我在这方面缺乏表现。我的意思是对于一些网站我无法获得所有照片。 $ url有示例外部网站,它没有给我所有的图像。

  $url
  ="http://www.target.com/c/baby-baby-bath-bath-safety
  /-/N-5xtji#?lnk=nav_t_spc_3_inc_1_1";
  $html = file_get_contents($url);
  $doc = new DOMDocument();
  @$doc->loadHTML($html);
  $tags = $doc->getElementsByTagName('img');

  foreach ($tags as $tag) {
      echo $imageUrl = $tag->getAttribute('src');
   echo "<br />";
  }

这是否可能我的功能/准确性与Firefox的选项相似

Firefox-&GT;工具 - &gt;页面信息 - &gt;媒体

我的意思是我只是想更加准确,因为现有的库并没有获取所有图像。我也尝试了file_get_content ...也没有获取所有图像。

2 个答案:

答案 0 :(得分:0)

您需要使用正则表达式来获取图像的src。 DOMDocument在内存中构建所有DOM结构,你不需要它。获取URL时,使用file_get_contents()并将数据写入文件。如果您要解析许多页面,也请添加max_execution_time

答案 1 :(得分:0)

  

从远程服务器下载图像

function save_image($sourcePath,$targetPath)
  { 

      $in  = fopen($sourcePath, "rb");
      $out = fopen($targetPath, "wb");
      while ($chunk = fread($in,8192))
      {
          fwrite($out, $chunk, 8192);
      }
      fclose($in);
      fclose($out);
  }

$src = "http://www.example.com/thumbs/thumbs-t2/1/ts_11083.jpg"; //image source
$target = dirname(__FILE__)."/images/pic.jpg"; //where to save image with new name
save_image($src,$target);