php foreach创建文件,php – mkdir()在foreach函数中跳过第一个文件

标签:php

我有一个脚本,它读取URL-Image-List并将图像保存在基于URL的文件夹中.

这是我的脚本:

// Open the URL and save each line in a array

$file = fopen("http://www.edem.de/php/imglist.ashx","r");

$fileArray = array();

while (($line = fgetss($file)) !== false) {

$fileArray[] = $line;

}

// Sort the array

array_multisort(array_values($fileArray), SORT_NUMERIC , array_keys($fileArray), SORT_NUMERIC , $fileArray);

// Start the iteration for saving each image

foreach ($fileArray as $url) {

// Explode URL for folder and image name

$urlpath = parse_url($url, PHP_URL_PATH);

$dataend = explode("/", $urlpath);

$ending = $dataend[5];

$folder = $dataend[3];

// delete "_" and "whitespace"

$folder = strtr($folder, "_", " ");

$folder = preg_replace('/\s+/', '', $folder);

$ending = strtr($ending, "_", " ");

$ending = preg_replace('/\s+/', '', $ending);

// Check if folder exist. If yes -> go on with path. If no -> create folder

if (!file_exists("Bilder/$folder/")) {

$imgpath = mkdir("Bilder/$folder/", 0777, true);

//I THINK THE MISTAKE IS HERE

}

else {

$imgpath = ('Bilder/' .$folder. '/');

}

// save the path and the image name in a variable

$savepath = $imgpath . $ending;

// Test echo

echo ("The image $ending is saved in the folder $savepath. The file should be in the folder $folder
");

//Connect and save images

$ch = curl_init($url);

curl_setopt($ch, CURLOPT_HEADER, 0);

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_BINARYTRANSFER,1);

$rawdata=curl_exec ($ch);

curl_close ($ch);

$fp = fopen(''.$savepath.'','w');

fwrite($fp, $rawdata);

fclose($fp);

}

每个文件夹应包含一些图像.

但是:当必须创建文件夹时,他会创建此文件夹,但将第一个图像保存在根目录中,而不是保存在此文件夹中.

示例回声

该文件夹已创建,但第一个图像未保存在此新文件夹中.

以下图像也属于此文件夹,可以正确保存.

我没有错.

解决方法:

在第一种情况下,您将其存储为true或false.更改以下内容:

// Check if folder exist. If yes -> go on with path. If no -> create folder

if (!file_exists("Bilder/$folder/")) {

$imgpath = mkdir("Bilder/$folder/", 0777, true);

//I THINK THE MISTAKE IS HERE

}

else {

$imgpath = ('Bilder/' .$folder. '/');

}

至:

// Check if folder exist. If yes -> go on with path. If no -> create folder

if (!file_exists("Bilder/$folder/")) {

mkdir("Bilder/$folder/", 0777, true);

}

$imgpath = ('Bilder/' .$folder. '/');

标签:php

来源: https://codeday.me/bug/20190528/1169923.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值