Create CSV File with PHP - php

I want to create a new .csv file (without opening the raw file first via fopen).
So far I have tried this:
$list[] = array
(
"Name" => "John",
"Gender" => "M",
"Age" => "21"
);
$timestamp0 = date("Y-m-d H:i:sa", time());
$datetime = new DateTime($timestamp0);
$datetime->setTimezone(new DateTimeZone('Asia/Jakarta'));
$timestamp = $datetime->format("Y-m-d_H-i");
$filename = __DIR__ . "/file/" . $timestamp . ".csv";
$header = array("name", "gender", "age");
file_put_contents($filename, implode("\n", $list)); // error here bcs array given :')
My questions are:
How can I change array 2d to csv?
Very need your help :( Thank you so much :")

Using fopen with w will create the file if does not exist:
$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];
$fp = fopen($filename, 'w');
//Write the header
fputcsv($fp, array_keys($list[0]));
//Write fields
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
If you don't like fputcsv and fopen you can use this alternative:
$list = [
["Name" => "John", "Gender" => "M"],
["Name" => "Doe", "Gender" => "M"],
["Name" => "Sara", "Gender" => "F"]
];
$csvArray = ["header" => implode (",", array_keys($list[0]))] + array_map(function($item) {
return implode (",", $item);
}, $list);
file_put_contents($filename, implode ("\n", $csvArray));
I hope this will help you.

You can use below code
$list[]=array ("name","gender","age"); // push header here
$list[] = array("John","M","21"); // push record here
$timestamp0 = date("Y-m-d H:i:sa",time());
$datetime = new DateTime($timestamp0);
$datetime->setTimezone(new DateTimeZone('Asia/Jakarta'));
$timestamp = $datetime->format("Y-m-d_H-i");
$filename = __DIR__ . "/file/" . $timestamp . ".csv";
$fp = fopen($filename, 'w');
foreach ($list as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
For more detail read php manual about CSV file. http://php.net/manual/en/function.fputcsv.php

Related

how to transpose CSV file with php

just wondering how I display the data in a CSV file diffrently, the code a have now
displays the data
like this inexcel/google
but I want to display the data in excel/google docs like this
This is the code I am using is there anyway to modify it to give me the result i want?
$data2 = [
["number of drinks:" => "1"],
["number of snacks:" => "2 "],
["number of cats" => "3"],
["numbers of dogs:" => "4"],
$fh = fopen('file.csv', 'w');
$headers = [];
$values = [];
foreach ( $data2 as $form_section ) {
foreach ( $form_section as $heading => $value ) {
array_push( $headers, $heading );
array_push( $values, $value );
}
}
fputcsv( $fh, $headers,);
fputcsv( $fh, $values,);
fclose($fh);
];
This should produce the array in the format needed to pass it to fputcsv.
$data2 = [
["number of drinks:" => "1"],
["number of snacks:" => "2 "],
["number of cats" => "3"],
["numbers of dogs:" => "4"],
];
$tmp = [];
$fh = fopen("file.csv", "w");
foreach($data2 as $row){
$header = key($row);
$value = $row[$header];
fputcsv( $fh, [$header, $value]);
}
fclose($fh);

Convert threeDimensionalArray to Two and save csv

I have problem with convert array. I have structure like as
$threeDimensionalArray = [
[
[
'name' => 'name1',
],
[
'name' => 'name2',
],
],
[
[
'time' => 123,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
[
'time' => 457,
'anyField'=>22222,
'anyField1'=>22222,
'anyField2'=>22222
],
],
];
I need convert this array to two dimensional and save each array to csv file via fputscsv
example
first line in CSV
'name1','name2',
second line
123, 457, etc
This solution will help in your specific case:
$to_csv = [];
foreach ($threeDimensionalArray as $first_level) {
foreach ($first_level as $second_level) {
foreach ($second_level as $key => $value) {
$to_csv[$key][] = $value;
}
}
}
$fp = fopen('file.csv', 'w');
foreach ($to_csv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
The idea is to firstly configure array to two layers array with grouping by key and use fputcsv() afterwards.
I resolve this problem :)
foreach ($threeDimensionalArray as $firstDimensional) {
$array= [];
foreach ($firstDimensional as $twoDimensional) {
$array[] = $twoDimensional['name'] ?? null .$twoDimensional['time'] ?? null;
}
fputcsv($fp, $array);
$returnArray[]=$array;
}

First key of php associative array returns undefined index when parsed from CSV

I am having trouble accessing the first index of an associative array when parsing from a csv.
CSV:
ID,COLOR
1,Red
2,Green
3,Blue
PHP:
function associative_array_from_csv($csv)
{
$rows = array_map('str_getcsv', file($csv));
$header = array_shift($rows);
$array = array();
foreach($rows as $data) {
$array[] = array_combine($header, $data);
}
return $array;
}
$colors = associative_array_from_csv($csv);
Now $colors returns:
[
[
"ID" => "1",
"COLOR" => "Red",
],
[
"ID" => "2",
"COLOR" => "Green ",
],
[
"ID" => "3",
"COLOR" => "Blue",
],
];
But if I try to access the ID of any color:
$colors[0]["ID"] // returns undefined index: ID
$colors[0]["COLOR"] // returns "Red"
If I loop over the colors I can access the ID like so:
foreach($colors as $color)
{
print_r(reset($color)); // Prints the ID
}
But why I can't access it directly like $colors[0]["ID"]?
Thanks
I had the same issue. The problem was that Excel adds a hidden character to the first cell in the document, for encoding UTF-8 BOM.
I could see this when running:
var_dump(json_encode($array));
This would return:
string(312) "[{"\ufeffemail":"test#me.com","firstName":"import","lastName":"test"},{"\ufeffemail":"test#comcast.net","firstName":"import","lastName":"test"}]"
To remove the \ufeff character, I did:
$header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
In this case, that would be:
function associative_array_from_csv($csv)
{
$rows = array_map('str_getcsv', file($csv));
$header = array_shift($rows);
$header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);
$array = array();
foreach($rows as $data) {
$array[] = array_combine($header, $data);
}
return $array;
}
This worked for me!
header = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $header);

Text File to Array

I am trying to put my text file into an array..
my text file content is like this:
TP-Link|192.168.1.247|CHANNEL 02|warehouse
Ruckus|192.168.1.248|CHANNEL 03|entrance
anyone can help me to make the output looks like this:
$servers = array(
array(
'name' => 'TP-Link',
'ip' => '192.168.1.247',
'channel' => 'CHANNEL 02',
'location' => 'warehouse',
),
array(
'name' => 'Ruckus',
'ip' => '192.168.1.248',
'channel' => 'CHANNEL 03',
'location' => 'entrance',
),
);
thanks in advance..
this is my code:-
$file="config/data.txt";
$fopen = fopen($file, r);
$fread = fread($fopen,filesize($file));
fclose($fopen);
$remove = "\n";
$split = explode($remove, $fread);
$servers[] = null;
$tab = "|";
foreach ($split as $string)
{
$row = explode($tab, $string);
array_push($servers,$row);
}
the problem is it outputs a multidimensional without array names..
and i am not familiar in multidimensional array..
You can do it like below:-
<?php
$data = file("your text-file path"); // file() read entire file into array
// now your array looks like below:-
$array = array('TP-Link|192.168.1.247|CHANNEL 02|warehouse',
'Ruckus|192.168.1.248|CHANNEL 03|entrance'); // comment this array line while using the code
$keys = array('name','ip','channel','location');
$final_array = array();
foreach ($array as $ar){
$explode = explode('|',$ar);
$final_array[] = array_combine($keys,$explode);
}
echo "<pre/>";print_r($final_array);
Output:-https://eval.in/734221
You can do something like this. Check out explode and fgets
<?php
$servers_array = array();
$handle = #fopen("inputfile.txt", "r");
if ($handle) {
while (($buffer = fgets($handle)) !== false) {
$line = explode("|", $buffer);
$servers_array[] = array(
"name" => $line[0],
"ip" => $line[1],
"channel" => $line[2],
"location" => $line[3],
)
}
fclose($handle);
}
?>
So if you have a text file consisting of the following, just use the following code to get the output that you want:
<?php
$str="TP-Link|192.168.1.247|CHANNEL 02|warehouse
Ruckus|192.168.1.248|CHANNEL 03|entrance";
echo '<pre>';
$sections=explode("\n",$str);
print_r($sections);
$finalArray=array();
foreach($sections as $line){
$finalArray[]=explode("|",$line);
}
print_r($finalArray);
?>
NOTE: $str is the text that you get from the text file

Bulk insert/export an array into a CSV file using PHP

I want to export an associative array into a .csv file. I'm using fputcsv() inside a foreach loop to insert the rows one at a time.
Here's my code:
$headers = array("Parent ID", "Company Name", "Created By", "Created Time", "Mandatory", "Valid", "Total Count", "Audit");
foreach ($cursorCount as $eachCursorCount) {
foreach ($cursor as $eachCursor) {
if ($eachCursorCount["createdBy"] == $eachCursor["createdby"]) {
$insertVal = array(
"parentid" => $eachCursor['parentid'],
"companyName" => $eachCursor['companyname'],
"createdby" => $eachCursor['createdby'],
"createdtime" => date('Y-m-d H:i:s', $eachCursor['createdtime']->sec),
"mandatory" => $eachCursor['mandatory'],
"valid" => $eachCursor['valid'],
"totalCount" => $eachCursorCount['totalCount'],
"audit" => $eachCursorCount['audit']
);
array_push($res_arr_values, array_values($insertVal));
}
}
}
}
$fp1 = fopen('export.csv', 'w');
fputcsv($fp1, $headers);
foreach ($res_arr_values as $fields)
{
fputcsv($fp1, $fields);
}
fclose($fp1);
Is there any method using which one can insert multiple rows at a time? (Or any other method with much lesser time complexity.)
Thank You.

Categories