Search code examples
phpstringcsvrequire-once

How to save php file as csv file?


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.


Solution

  • 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