Foreach循环只迭代一次-PHP

Foreach循环只迭代一次-PHP,php,foreach,copy,domdocument,explode,Php,Foreach,Copy,Domdocument,Explode,我正在寻找一个PHP脚本,从一些网站抓取图像,但我找不到一个通用的,允许多页抓取。。所以我建了一个 它要求保存到路径和一个要从中刮取图像的网页列表,以逗号分隔。脚本用逗号分解用户输入的网页,然后循环遍历每个网页。它总是能很好地抓取第一个网页,但随后会跳过其余的网页 这是整个脚本。请随意将其复制到localhost并运行,您将明白我的意思 <?php error_reporting( 0 ); if(isset($_POST['doit'])){ $scrapethese = ex

我正在寻找一个PHP脚本,从一些网站抓取图像,但我找不到一个通用的,允许多页抓取。。所以我建了一个

它要求保存到路径和一个要从中刮取图像的网页列表,以逗号分隔。脚本用逗号分解用户输入的网页,然后循环遍历每个网页。它总是能很好地抓取第一个网页,但随后会跳过其余的网页

这是整个脚本。请随意将其复制到localhost并运行,您将明白我的意思

<?php
error_reporting( 0 );

if(isset($_POST['doit'])){
    $scrapethese = explode(",",$_POST['website']);
    foreach($scrapethese as $scrapethis){
        $cleanit = str_replace(" ", "", $scrapethis);
        $html = file_get_contents($cleanit);
        $dom = new domDocument;
        $dom->loadHTML($html);
        $dom->preserveWhiteSpace = false;
        $imgs = $dom->getElementsByTagName('img');
        foreach($imgs as $img){
            $fullimgpath = $img->getAttribute('src');
            $slashexp = explode('/', $fullimgpath);
            $lastindex = count($slashexp)-1;
            $shortpath = $slashexp[$lastindex];
            $filename = $_POST['folder']."\\".$shortpath;
            if(copy($fullimgpath, $filename)){
                echo $slashexp[$lastindex]." Saved<br />";
            }else{
                echo "<b style='color:red;'>Could not save img: </b>".$filename."<br />";
            }
        }
    }
}else{
?>
<form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
    <input type="hidden" name="doit" value="x" />
    <label>The complete path to the page you'd like to scrape. You may enter multiple paths seperated by commas.</label><br />
    <textarea name="website" /></textarea><br />
    <label>Path to the folder you want to save images to</label><br />
    <input type="text" name="folder" /><br />
    <input type="submit" value="save all images" />
</form>
<?php
}
?>
“>
要刮取的页面的完整路径。您可以输入多个以逗号分隔的路径。

要将图像保存到的文件夹的路径


如果有人能提供一些见解,解释为什么脚本在提供多个站点时没有在所有网站上循环,我将非常感谢。

var_dump($imgs);查看它是否实际从$dom->getElementsByTagName()返回数组/对象或者,如果它只是返回一个或一个字符串。您可能需要进行一些预分解,以将IMG作为数组/对象,您可以通过每个数组/对象进行分解。当我vardump它时,我会得到
对象(DOMNodeList)[2]
。但我得到过一次,因为var_dump应该打印两次,因为有两个网页,所以循环应该迭代两次。所以,你的主循环失败了,而不是img get循环是$scrapeThes实际上是一个数组?正确,
foreach($scrapeThes as$scrapeThes)是给我带来麻烦的部分,你应该考虑使用换行符作为TexTaRa中的分隔符而不是逗号。逗号可以合法地出现在URL中未编码,但是换行符不能。