output rows to csv - php

I have a script that successfully prints a header and rows in the terminal output, but when I try to do the same thing for a CSV output it fails and says it expects an array.
I want to try to get lined up for just a simple csv that would ideally open in excel with different columns
print("Frame,Group,Average Days,Total Units Sold,Total Placements\n");
//$file = fopen("contacts.csv","w");
foreach($groupedByFrame as $frame){
print($frame['frame'].','.$frame['group'].','.round($frame['avg'],3).','.$frame['qty'].','.$frame['placements']."\n");
//fputcsv($file,explode(',',$frame));
}
//fclose($file);

If you want to change the format (and order) of the $frame array, you could create another one:
$file = fopen("contacts.csv","w");
// header
$header = ['Frame','Group','Average Days','Total Units Sold','Total Placements'];
fputcsv($file, $header);
// data
foreach($groupedByFrame as $frame)
{
$array = [
$frame['frame'],
$frame['group'],
round($frame['avg'],3),
$frame['qty'],
$frame['placements']
];
fputcsv($file, $array);
}
fclose($file);
If you want to output the $frame directly, you could use:
$file = fopen("contacts.csv","w");
$header = ['Frame','Group','Average Days','Total Units Sold','Total Placements'];
fputcsv($file, $header);
foreach($groupedByFrame as $frame)
{
fputcsv($file, $frame);
}
fclose($file);

You don't need to explode the inner array, it's already an array.
Try this:
//print("Frame,Group,Average Days,Total Units Sold,Total Placements\n");
$file = fopen("contacts.csv","w");
foreach($groupedByFrame as $frame)
{
//print($frame['frame'].','.$frame['group'].','.round($frame['avg'],3).','.$frame['qty'].','.$frame['placements']."\n");
fputcsv($file,$frame);
}
fclose($file);

Related

how to convert php file into csv

$lang['add_a']="Add a";
$lang['ban_zon_link']="Banner, Zone linking";
$lang['ban_zon_link_help']="Zones linking with Banners";
$lang['manage_ban_zon_link_help']="Manage banner zone linking -";
$lang['adtag']="Ad Tag";
I saved above lines into php file as lang.php need to convert php file into csv in code level.
You could open the file as csv, iterate over your array and use fputcsv
foreach($lang as $myrow) {
fputcsv($output, $myrow);
}
http://php.net/manual/en/function.fputcsv.php
You can use fputcsv:
<?php
$lang = ...
$fp = fopen('file.csv', 'w');
// Insert array keys as CSV header
fputcsv($fp, array_keys($lang);
// Insert values as first data row
fputcsv($fp, array_values($fields));
fclose($fp);
?>
This works if you have only row record in your $lang array as your example suggests. This will create a 2 rows CSV with an header (the keys of the $lang array) and one data row (the values of the array.
If you are aiming at a different thing please clarify your question.
include("lang.php");
foreach($lang as $l)
{
file_put_contents("csv_file.csv",$l.",",FILE_APPEND);
// csv_file.csv is the name of your file
}
file_put_contents("csv_file.csv","\n",FILE_APPEND);
try with this:-
/* $lang['add_a']="Add a";
$lang['ban_zon_link']="Banner, Zone linking";
$lang['ban_zon_link_help']="Zones linking with Banners";
$lang['manage_ban_zon_link_help']="Manage banner zone linking -";
$lang['adtag']="Ad Tag";*/
if above php code in lang.php:-
require_once "lang.php";
$fp = fopen('file.csv', 'w');
fputcsv($fp, array_keys($lang));
fputcsv($fp, array_values($lang));
fclose($fp);
To read in a PHP script and write it out, I've done the following...
<?php
$file="part1.php";
$outFile="part1.csv";
$in = file($file);
$out = fopen($outFile, "w");
foreach($in as $line ) {
$parts = explode("=", $line);
if ( count($parts) == 2 ) {
fputcsv($out, array($parts[0],"=",rtrim($parts[1],";".PHP_EOL)));
}
}
fclose($out);
which for your example ( as part1.php) gives...
$lang['add_a'],=,"""Add a"""
$lang['ban_zon_link'],=,"""Banner, Zone linking"""
$lang['ban_zon_link_help'],=,"""Zones linking with Banners"""
$lang['manage_ban_zon_link_help'],=,"""Manage banner zone linking -"""
$lang['adtag'],=,"""Ad Tag"""
$file = 'file.csv';
header( "Content-Type: text/csv;charset=utf-8" );
header( "Content-Disposition: attachment;filename=\"$file\"" );
header("Pragma: no-cache");
header("Expires: 0");
$fp= fopen('php://output', 'w');
foreach ($lang as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);
exit();

Convert xml to csv with php With this type of structure

I need to parse this xml structure to a csv separated data by columns (;) But it does not work, just create the header without the data
----<ArticuloD>
<codigo>10202</codigo>
<familia>VARIOS</familia>
<subfamilia>LIBROS</subfamilia>
<subfamilia2>LIBROS</subfamilia2>
<subfamilia3>LIBROS</subfamilia3>
<subfamilia4>LIBROS</subfamilia4>
<ean>9788425351501</ean><talla>ST</talla>
----</ArticuloD>
---<ArticuloD>
My php code:
<?php
$file='ListaArticulosD-507.xml';
if (file_exists($file)) {
$xml = simplexml_load_file($file);
$f = fopen('user.csv', 'w');
// array to hold the field names
$headers = array();
// loop through the first set of fields to get names
foreach ($xml->ArticulosD->ArticuloD->children() as $field) {
// put the field name into array
$headers[] = $field->getName();
}
// print headers to CSV
fputcsv($f, $headers, ';', '"');
foreach ($xml->ArticuloD->children() as $users) {
fputcsv($f, get_object_vars($users), ';', '"');
}
fclose($f);
}
?>
Your last foreach loop is going too far down into the structure, if you change it to...
foreach ($xml->ArticuloD as $users) {
Then the output I get is
codigo;familia;subfamilia;subfamilia2;subfamilia3;subfamilia4;ean;talla
10202;VARIOS;LIBROS;LIBROS;LIBROS;LIBROS;9788425351501;ST
Sometimes using print_r() when your fetching data like this can give you a hint as to what your working with at each point. Just remember to take them out before delivering any code!

how can I sort a text file in php

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt

Array to CSV file for vertical layout and failed to put the header row

I have a problem to create a horizontal layout for the csv
here is an array which I have convert it to json-format
{"datetime":["2000-01-01","2000-01-02","2000-01-03","2000-01-04","2000-01-05","2000-01-06","2000-01-07","2000-01-08","2000-01-09","2000-01-10","2000-01-11","2000-01-12","2000-01-13","2000-01-14","2000-01-15","2000-01-16","2000-01-17","2000-01-18","2000-01-19","2000-01-20","2000-01-21","2000-01-22","2000-01-23","2000-01-24","2000-01-25","2000-01-26","2000-01-27","2000-01-28","2000-01-29","2000-01-30","2000-01-31","2000-02-01","2000-02-02","2000-02-03","2000-02-04","2000-02-05","2000-02-06","2000-02-07","2000-02-08","2000-02-09","2000-02-10","2000-02-11","2000-02-12","2000-02-13","2000-02-14","2000-02-15","2000-02-16","2000-02-17","2000-02-18","2000-02-19","2000-02-20","2000-02-21","2000-02-22","2000-02-24","2000-02-25","2000-02-26","2000-02-27","2000-02-28","2000-02-29","2000-03-01","2000-03-02","2000-03-03","2000-03-04","2000-03-05","2000-03-06","2000-03-07","2000-03-08","2000-03-09","2000-03-10","2000-03-11","2000-03-12","2000-03-13","2000-03-14","2000-03-15","2000-03-16","2000-03-17","2000-03-18","2000-03-19","2000-03-22","2000-03-23","2000-03-24","2000-03-28","2000-03-29","2000-03-30","2000-03-31","2000-04-01","2000-04-02","2000-04-03","2000-04-04","2000-04-05","2000-04-06","2000-04-07","2000-04-08","2000-04-09","2000-04-10","2000-04-11","2000-04-12","2000-04-13","2000-04-14","2000-04-15","2000-04-16","2000-04-17","2000-04-18","2000-04-19","2000-04-20","2000-04-21","2000-04-22","2000-04-23","2000-04-24","2000-04-25","2000-04-26","2000-04-27","2000-04-28","2000-04-29","2000-04-30","2000-05-01","2000-05-02","2000-05-03","2000-05-04","2000-05-05","2000-05-06","2000-05-07","2000-05-08","2000-05-09","2000-05-10","2000-05-11","2000-05-12","2000-05-13","2000-05-14","2000-05-15","2000-05-16","2000-05-17","2000-05-18","2000-05-19","2000-05-20","2000-05-21","2000-05-22","2000-05-23","2000-05-24","2000-05-25","2000-05-26","2000-05-27","2000-05-28","2000-05-29","2000-05-30","2000-05-31","2000-06-01","2000-06-02","2000-06-03","2000-06-04","2000-06-05","2000-06-06","2000-06-07","2000-06-08","2000-06-09","2000-06-10","2000-06-11","2000-06-12","2000-06-13","2000-06-14","2000-06-15","2000-06-16","2000-06-17","2000-06-18","2000-06-19","2000-06-20","2000-06-21","2000-06-22","2000-06-23","2000-06-24","2000-06-25","2000-06-26","2000-06-27","2000-06-28","2000-06-29","2000-06-30","2000-07-01","2000-07-02","2000-07-03","2000-07-04","2000-07-05","2000-07-06","2000-07-07","2000-07-08","2000-07-09","2000-07-10","2000-07-11","2000-07-12","2000-07-13","2000-07-14","2000-07-15","2000-07-16","2000-07-17","2000-07-18","2000-07-19","2000-07-20"],"Reservoir Level":["102.95","103.01","103.05","102.93","102.78","102.83","102.78","102.87","102.92","102.97","103.02","103.05","103.29","103.3","103.29","103.15","103","102.92","102.95","102.98","102.9","102.8","102.8","102.81","102.86","102.9","102.92","102.94","102.96","102.98","102.99","102.99","102.3","103","103.02","103.03","103.04","103.05","103.05","103.06","103.1","103.15","103.19","103.19","103.2","103.3","103.32","103.33","103.34","103.19","102.98","102.89","102.89","102.91","102.96","103.05","103.06","103.07","103.27","103.31","103.28","103.12","102.95","102.94","102.97","102.98","103.02","103.02","103.08","103.14","103.18","103.54","103.57","103.48","103.35","103.21","103.12","103.2","103.3","103.38","103.4","103.4","103.4","103.4","103.4","103.34","103.34","103.27","103.27","103.28","103.28","103.3","103.3","103.3","103.3","103.25","103.2","103.2","103.14","103.14","103.1","103.1","103","103","103.25","103.25","103.35","103.35","103.45","103.45","103.5","103.5","103.46","103.46","103.37","103.37","103.26","103.26","103.22","103.22","103.26","103.31","103.31","103.49","103.49","103.34","103.34","103.19","103.19","103.21","103.21","103.27","103.27","103.33","103.37","103.37","103.42","103.42","103.33","103.33","103.26","103.26","103.19","103.19","103.35","103.35","103.48","103.48","103.55","103.55","103.55","103.6","103.46","103.46","103.46","103.33","103.33","103.33","103.62","103.62","103.62","103.62","103.6","103.5","103.5","103.38","103.38","103.24","103.24","103.26","103.26","103.3","103.3","103.2","103.2","103.16","103.23","103.23","103.26","103.26","103.29","103.29","103.31","103.31","103.32","103.32","103.35","103.35","103.37","103.42","103.42","103.3","103.3","103.25","103.25","103.28","103.28","103.3","103.3","103.31","103.31","103.25","103.25","103.18","103.18","103.18","103.18","103.22","103.12","103.13","103.14","103.16","103.23","103.65","103.52","104.03","103.84","103.68","103.59","103.45","103.31","103.2","103.11","103.13","103.15","103.19","103.22","103.25","103.27","103.29","103.3","103.32","103.24","103.13","103.12","103.17","103.21","103.25","103.15","103.04","103.07","103.09","103.1","103.11","103.11","103.11","103.1","103.05","103.08","103.1","103.11","103.11","103.11","103.1","103.1","103.11","103.13"],"Rainfall":[null,"14.5","4.5","7","2.5","54",null,"18","2",null,"1",null,"24.5","9",null,null,null,null,null,"0.5",null,null,null,null,"10.5",null,null,null,null,null,null,null,null,null,null,null,"5",null,null,null,"17.5","7.5",null,null,"7","20",null,null,null,null,null,null,null,"5","10","9.5","0","0","45","0","42","0","0","0","0","2.5","27.5","0","29","39","2","93","6","0","0","14","0","8.5","0","43.5","31.5","0","0","32","32","0","0","2","2","14","14","20","20","4","4","0","0","5.5","5.5","0","0","17.5","17.5","0","0","16","16","0","0","14","14","0","0","0.5","0.5","0","0","0","0","0","0","8","8","3.5","3.5","69.5","69.5","0","0","0","0","39.5","39.5","5","5","9","9","1","1","0","0","6.5","6.5","11.5","11.5","14.5","14.5","0","0","0","0","0","0","0","21.5","21.5","21.5","0","0","0","0","0","0","54.5","54.5","0","0","14.5","14.5","12","12","0","0","0","0","0","0","0","0","0","0","0","0","31.5","31.5","0","0","0","0","0","0","0","0","0","0","0","0","24.5","24.5","0","0","18","18","0","0","12.5","12.5","6.5","6.5","1","1","0","0","0","0","0","0.5","0","0","12.5","1","57.5","0","63","0","0","40","5.5","0","0","0","0","0","0.5","0.5","0","0","0","0","12.5","2.5","0.5","1","27","11","3.5","13","0","4.5","0","0","0","0","0","0","0","0","0","1.5","0","0","0","0","2","9.5"]}
and here I have a develop a simple function to output it as csv
function convert_to_csv($input_array, $output_file_name, $delimiter) {
$temp_memory = fopen('php://memory', 'w');
foreach ($input_array as $key => $set) {
fputcsv($temp_memory, $set, $delimiter, '"');
}
fseek($temp_memory, 0);
header('Content-Type: application/csv');
header('Content-Disposition: attachement; filename="' . $output_file_name . '";');
fpassthru($temp_memory);
}
here the layout that i don't want it to be
and this is the layout that I want it to be
as you can see I failed to find a way to put the header row. Appreciate your helps. Thanks
You need transposition.
foreach($input_array as $key=>$set){
foreach($set as $row=>$val){
$lines[$row][$key] = $val;
}
}
For input_array like:
{"datetime":["2000-01-01","2001-01-01"], "Resovior":[1,2], "RainFall":[2,2]}
will produce $lines like
$lines[0]: {"datetime": "2000-01-01", "Resovior": 1, "RainFall": 2}
$lines[1]: {"datetime": "2001-01-01", "Resovior": 2, "RainFall": 2}
Keep in mind that every element of $lines refers to one row in your file, and its' elements are the columns.
Then you can put rows like this:
foreach ($lines as $line)
{
fputcsv($temp_memory,$line,$delimeter,"'");
}
The way to add a header is the same.
$header = array("DateTime", "Revisior", "Rainfall");
fputcsv($temp_memory, $header, $delimeter, "'");
Your output file is wrong formatted, must be like that:
DateTime;Reservoir;Rainfall;
date1;res1;rain1;
date2;res2;rain2;
date3;res3;rain3;
but your current file looks like this one:
date1;date2;date3;
res1;res2;res3;
rain1;rain2;rain3;
You must iterate trough array recursively in order to set the correct format.
A possible solution (taken from https://stackoverflow.com/a/6600130/3518053 ) :
$fh = fopen('file.csv', 'w');
// write out the headers
fputcsv($fh, array_keys($data));
// write out the data
for ($i = 0; $i < count($data['dates']); $i++) {
$temp = array($data['dates'][$i], $data['type1'][$i], $data['type2'][$i]);
fputcsv($fh, $temp);
}
Regards

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

Categories