CSV data to array_map and str_getcsv using delimiter - php

My problem is I'm unable to pass 2nd parameter to str_getcsv function.
$rows = array_map('str_getcsv', file($filePath_product_names_t), [";"]);
$header = array_shift($rows);
$csv = [];
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
CSV structure
"25";"some text"; "also some Text"
And also getting WARNING:
array_combine(): Both parameters should have an equal number of
elements

Try this:
$rows = array_map(function($v){return str_getcsv($v, ";");}, file($filePath_product_names_t));
$header = array_shift($rows);
$csv = [];
foreach($rows as $row) {
$csv[] = array_combine($header, $row);
}
print_r($rows);

Combining the two problems, the first is that you can't pass a parameter the way you are trying in the array_map() so as in the link I posted in the comments, you can create an anonymous function to do this.
The second is that, in some cases a CSV file doesn't always have all the data for a row in the file. In this case the header row and the other rows don't have the same amount of data, so use array_pad() to add blanks to make sure they do have the same length. To combine these into the code...
$rows = array_map(function($data) { return str_getcsv($data,";");}
, file($filePath_product_names_t));
$header = array_shift($rows);
$csv = [];
foreach($rows as $row) {
$row = array_pad($row, count($header), "");
$csv[] = array_combine($header, $row);
}
print_r($csv);

Related

Create key-value pair from csv php

I have a csv file like below
tl_blade_thickness,tl_blade
test1,test1
test2,test2
test3,test3
test4,test4
test5,test5
test6,test6
test7,test7
test8,test8
test9,test9
I'm trying to create a key value pair array like below.
["tl_blade_thickness"=>["test1","test2","test3",...],tl_blade=>["test1","test2","test3",...]]
I tried like this below.
$content = fopen("csv.csv", "r");
$all_rows = array();
$header = fgetcsv($content);
while ($row = fgetcsv($content)) {
$all_rows[] = array_combine($header, $row);
}
Use the first line of the file to create the keys of the array. Then push each field of the remaining lines into the corresponding element keys.
$content = fopen("csv.csv", "r");
$headers = fgetcsv($content);
$all_rows = array_fill_keys($headers, []);
while ($row = fgetcsv($content)) {
foreach ($headers as $i => $name) {
$all_rows[$name][] = $row[$i];
}
}

PHP Read csv data without first line

I want to store csv columns data into array
I have did this so far.
$csvfile = file('testfile.csv');
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}
This works fine but the first line also include in array
I want to skip first line
Remove the first element of the array with array_shift().
$csvfile = file('testfile.csv');
array_shift($csvfile);
$csvData = array_map('str_getcsv', $csvfile);
or you can do like this
$csvfile = file('testfile.csv');
unset($csvfile[0]);
$csvData = [];
foreach ($csvfile as $key => $line) {
$csvData[] = str_getcsv($line);
}

replicate/duplicate/clone a mysql_result object

I'm trying to save into file a mysql SELECT query as follows:
$result = mysqli_query($db,$sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result -> fetch_row()) {
fputcsv($out,$row);
}
fclose($out);
after save I need to publish on a page as follows :
while ($row = mysqli_fetch_assoc($result)) {
//embed html code
}
The problem is that anytime I run $result->fetch_row(), a record of data is lost. I need to be able to run fetch_object at least 2 times within my code and preserve the data. I thought cloning would be a good solution for this, but it isn't.
Any hints, other that doing 2 query on the sql database ?
I believe another solution that could work is to use mysqli_data_seek.
The mysqli_result object is a pointer that moves through the data with each call of fetch_row(), but you can move the pointer back to the beginning by calling
mysqli_data_seek($result, 0);
And now the result is "reset", as it were, and you can use it again.
Learn more here:
https://www.php.net/manual/en/mysqli-result.data-seek.php
If you need to re-use the data, load it into an array - or do all the logic in the same loop.
So for example,
$data = []:
$result = $mysqli->query("...");
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ($data as $row) {
fputcsv($out, $row);
}
fclose($out);
// ...
foreach ($data as $row) {
//embed html code
}
Or do it all in the same loop (this may not always be possible, so if it isn't, go with the option above).
$result = mysqli_query($db, $sql);
$out = fopen('tmp/csv.csv', 'w');
while ($row = $result->fetch_row()) {
fputcsv($out,$row);
// embed HTML
}
fclose($out);
If you have mysqlind installed as part of your PHP MySQL infrastructure, Use a fetch_all() to get all the results into an array. You can then use that array as many times as you like.
$result = mysqli_query($db,$sql);
$all_results = $result->fetch_all();
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}
Then you can reuse $all_results
If you dont have mysqlind then write a simple loop to load an array manually with all the results from the resultset
$result = mysqli_query($db,$sql);
$all_results = [];
while ($row = $result -> fetch_assoc()) {
$all_results[] = $row;
}
$out = fopen('tmp/csv.csv', 'w');
foreach ( $all_results as $row){
fputcsv($out,$row);
}
fclose($out);
// now to reuse the array for your HTML output
foreach ($all_results as $row) {
//embed html code
}

How to convert JSON data to CSV format on the fly with out using csv file

I am using PHP and converting the JSON data into the CSV format and later on read the same CSV file for further processing.
Below is my code that converts the JSON data in to the CSV format.
function LoadDataFromFile($file)
{
$json = file_get_contents($file);
$array = json_decode($json, true);
$f = fopen('out.csv', 'w');
$firstLineKeys = false;
$keys = array();
//first collect keys
foreach($array as $line){
foreach($line as $key => $value){
if(!in_array($key, $keys))
$keys[] = $key;
}
}
$keyString = implode(",", $keys);
fwrite($f, "$keyString\n");
foreach ($array as $line)
{
$outputArray = array();
foreach($keys as $key){
if(array_key_exists($key, $line)){
$outputArray[] = str_replace(',', '', $line[$key]);;
} else {
$outputArray[] = "";
}
}
$outputString = implode(",", $outputArray);
fwrite($f, "$outputString\n");
}
fclose($f);
}
As we can see that, i am writing data into the "out.csv" file, and later on i am reading same CSV file and assign the value/ full contents of the same file line by line to $array variable, as shown below.
$array = explode("\n", file_get_contents('out.csv'));
Now, I want to directly assign the value of csv contents into the $array variable with out using the intermediate "out.csv" file.
Wondering what data structure should i use while converting JSON data to CSV format, and possible code changes required for "LoadDataFromFile" method?
If you can already convert the json into csv, then just append the output strings together assigned to a string variable instead of writing it to a file. Or am I misunderstanding what you want?
Instead of:
fwrite($f, "$outputString\n");
you can put:
$csv .= $outputString;
And finish it with:
$array = explode("\n", $csv);

PHP read in specific csv file column as an array

I am new to PHP and would like to be able to read in a csv file which has two columns, one is the number (kind of like a ID) then the other holds a integer value. I have looked up the fgetcsv function but I have not been able to find a way to read a specific column from the csv file.
I would like to get all the values from the second column only, without the heading.
Any way of doing this?
This is what I have so far:
$file = fopen('data.csv', 'r');
$line = fgetcsv($file);
And this is some sample data from the csv file:
ID,Value
1,243.00
2,243.00
3,243.00
4,243.00
5,123.11
6,243.00
7,180.00
8,55.00
9,243.00
Any help would be appreciated.
Thanks.
fgetcsv() only reads a single line of the file at a time. You'll have to read the file in a loop to get it all:
$data = array();
while($row = fgetcsv($file)) {
$data[] = $row;
}
The heading you can skip by doing an fgetcsv once outside the loop, to read/trash the header values. And if you only want the second column, you can do:
$data[] = $row[1];
However, since you've got data in there, maybe it might be useful to keep it, plus key your new array with the ID values in the csv, so you could also have:
$data[$row[0]] = $row[1];
and then your nice shiny new array will pretty much exactly match what's in the csv, but as an array keyed by the ID field.
$csv = array_map("str_getcsv", file("data.csv", "r"));
$header = array_shift($csv);
// Seperate the header from data
$col = array_search("Value", $header);
foreach ($csv as $row) {
$array[] = $row[$col];
}
// Iterate through data set, creating array from Value column
$header = fgetcsv($h);
$rows = array();
while ($row = fgetcsv($h)) {
$rows []= array_combine($header, $row);
}
$fp = fopen($filePath, "r+");
$header = fgetcsv($fp);
while ($members = fgetcsv($fp)) {
$i = 0;
foreach ($members as $mem) {
$membersArray[ $i ][ ] = $mem;
$i++;
}
}
$newArray = array_combine($header, array_map("array_filter",$membersArray));
You can also use this class http://code.google.com/p/php-csv-parser/
<?php
require_once 'File/CSV/DataSource.php';
$csv = new File_CSV_DataSource;
$csv->load('data.csv');
var_export($csv->connect());
?>

Categories