2

For some background I have a bit of code that I am using to generate html files that contain a link to a unique code. Ultimately this ends up on a USB drive thats distributed to customers. This is done in batch so i can create as many custom files with code as needed.

if ( !empty($_POST) ) {

$url = trim($_POST['url']);

$codes = trim($_POST['codes']);

$codes_array = explode("\n", $codes);

$codes_array = array_filter($codes_array, 'trim');

foreach ($codes_array as $code) {

    $html = <<<EOD
<html>
<head></head>
<body>
<a href="$url$code">Download Now</a>
</body>
</html>
EOD;

    file_put_contents("codes/".$code.".html",$html);

}

}

What happens is only one file is generated in that folder, but its name is always the last element in the array, the other files don't get generated, it seems like the files getting overwritten even though $code is different on each iteration.

I tried the following code as well with same results.

$fh = fopen("codes/".$code.".html", "w+");
fwrite($fh, $html);
fclose($fh); 

Any ideas?

4

2 回答 2

1

代替

$codes_array = array_filter($codes_array, 'trim');

$codes_array = array_map('trim', $codes_array);

否则,只有最后一个元素不会有\n结尾。

于 2015-05-21T16:00:53.063 回答
0

你试试:

foreach ($codes_array as $key => $value ) {

    $html = <<<EOD
<html>
<head></head>
<body>
<a href="$url$code">Download Now</a>
</body>
</html>
EOD;

    file_put_contents("codes/".$value.".html",$html);

}

结果是一样的吗?

于 2015-05-21T16:07:47.383 回答