如何将 php 文件保存为 csv 文件?

How to save php file as csv file?

script1.phpreturns 结果:

helen,hunt
jessica,alba

script2.php returns 结果:

bradley,cooper
brad,pitt

script.php 看起来像这样

<?php
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
?>

并将return

name,surname
helen,hunt
jessica,alba
bradley,cooper
brad,pitt

问题

也许这对某些人来说是显而易见的,但我纠结了一段时间如何将这个 php 文件:script.php 保存为 csv 文件? script1.php 和 script2.php 都在 while 循环中产生结果,所以我可以将结果保存为 while 循环内的数组,但是希望有人能为我的原始问题提供一个简单的解决方案。

如果我没看错,您正在尝试将这些脚本的输出保存到 CSV 文件中。 尝试做:

ob_start();
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
$result = ob_get_contents();
file_put_contents('filename.csv', $result)

你也可以看看fputcsv:http://php.net/manual/en/function.fputcsv.php

如果你的问题是如何访问终端,那么就执行它

php -f script.php > file.csv

如果您想从脚本中执行此操作,可以使用 output buffering。它将遵循:

<?php
ob_start();
echo "name,surname";
require_once('script1.php');
require_once('script2.php');
$size=ob_get_length();
if ($size > 0)
{
    $content = ob_get_contents();
    // save $content to file here
    ob_clean();
}
?>

或者,如果您可以更改 script1.phpscript2.php,让它们打开文件以追加 (fopen('fname.csv', 'a')),然后写入该文件,将导致他们两个的行都写入文件而不相互覆盖。