1

script1.php returns results:

helen,hunt
jessica,alba

script2.php returns results:

bradley,cooper
brad,pitt

script.php looks like this

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

and will return

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

Question

Maybe this is obvious to someone, but I am struggling for a while how to save this php file: script.php as csv file? script1.php and script2.php both produce result over while loop, so I would be able to save results as array inside of a while loop however hopefully someone will offer an easy solution to my original question.

newbie_girl
  • 353
  • 1
  • 3
  • 15

2 Answers2

1

If I get it right, you are trying to save the output of those scripts to a CSV file. Try doing:

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

You can also take a look at fputcsv: http://php.net/manual/en/function.fputcsv.php

Fechy
  • 46
  • 3
0

If your question is how to do it having the access to the terminal, then just execute it

php -f script.php > file.csv

If you want to do it from the script, you can use output buffering. It will be along the lines of:

<?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();
}
?>

Or, alternatively, if you can change script1.php and script2.php, make them open the file for appending (fopen('fname.csv', 'a')), and write to that file, it will result in rows from both of them written to the file without overwriting each other.

Ishamael
  • 12,583
  • 4
  • 34
  • 52
  • i dont see the point of echo then output buffering when you could just write to the file directly. –  Nov 01 '16 at 20:52
  • Presumably the question is "script1.php and script2.php are out of my control, and they already echo it, how do I print that to file" – Ishamael Nov 01 '16 at 20:53
  • I assumed _both produce result over while loop, so I would be able to save results as array inside of a while loop **however hopefully someone will offer an easy solution to my original question**_ – AbraCadaver Nov 01 '16 at 20:53
  • @AbraCadaver: indeed. Put an alternative solution at the end, though it might not be how people actually do it in PHP. – Ishamael Nov 01 '16 at 20:56