【问题标题】:How to output the function into a File如何将函数输出到文件中
【发布时间】:2013-12-26 11:27:12
【问题描述】:

我有这个功能:

function permGen($a,$b,$c,$d,$e,$f,$g) {
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
            print trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
            }
        }
    }
}

这是我需要的输出,当我在屏幕上打印时效果很好。

假设,我定义了所有参数没有任何问题。现在问题来了,当我把 permGen($arguments....);有用。但是当我尝试通过这样的文件处理将其写入文件时,

$handle = fopen('new.txt', 'w+');
fwrite($handle, permGen($arguments...));

它似乎不起作用。它创建一个文件,但其中没有任何内容。我尝试用返回替换打印。然后它只在 new.txt 中给出了 1 个循环,没有别的。似乎没有什么能按照我想要的输出来工作。

谢谢

【问题讨论】:

  • 例如使用file_put_contents()。不要忘记FILE_APPEND 标志
  • 是的,使用file_put_contents()。稍后,要检索您存储的数据,您可以使用file_get_content()。欲了解更多信息,请参阅:php.net/file_put_contents | php.net/file_get_contents
  • file_put_contents() 不起作用。我试过:file_put_contents('new.txt',normGen($arguments...));不工作
  • Print 将内容输出到浏览器。因此,您的函数不返回任何内容,这就是您的文件中没有任何内容的原因。使用chanchal的方法

标签: php function return fopen


【解决方案1】:
function permGen($handle, $a,$b,$c,$d,$e,$f,$g) {
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
                fwrite(
                    $handle, 
                    trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
                );
            }
        }
    }
}

// To write to a file
$handle = fopen('new.txt', 'w+');
permGen($handle, $other, $arguments, ...);
fclose($handle);

// To write to normal output (browser, whatever)
$handle = fopen('php://output', 'w');
permGen($handle, $other, $arguments, ...);
fclose($handle);

编辑

如果您不想以任何方式修改函数,则可以使用输出缓冲来捕获打印输出:

ob_start();
permGen($arguments...);
$output = ob_get_contents();
ob_end_clean();

file_put_contents(
    'new.txt',
    $output,
    FILE_APPEND
);

【讨论】:

  • 您好先生,我不想篡改我的功能。也就是说,我不想同时创建文件。我想把我的输出的内容。 :)
  • 非常感谢!这正是我想要的:)
【解决方案2】:
function permGen($a,$b,$c,$d,$e,$f,$g) {
    $output = '';
    foreach ($a as $key1 => $value1){
        foreach($b as $key2 => $value2){
            foreach($c as $key3 => $value3) {
                $output .= trim($d[rand(0,count($d)-1)]).trim($value1).trim($e[rand(0,count($e)-1)]).trim($value2).trim($f[rand(0,count($f)-1)]).trim($value3).$g;
            }
        }
    }

    return $output;
}

【讨论】:

  • 您好,这不起作用。你不能像那样定义一个未定义的 $output
  • 在哪里看到未定义的 $output?
  • 我也查过了,只是输出函数,文件里没有写函数。
  • 你能把你的文件内容粘贴到这里吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
  • 2011-04-25
  • 1970-01-01
  • 2019-01-14
  • 1970-01-01
相关资源
最近更新 更多