read the csv file column wise - php

I want to read the csv file column wise and get the every column data into specified array
[country]
Array(
[0]=>Australia
)
[city]
Array(
[0]=>vic
)

you can use the fgetcsv function:
if (($handle = fopen("inputfile.csv", "r")) !== false) {
$filesize = filesize("inputfile.csv");
$firstRow = true;
$aData = array();
while (($data = fgetcsv($handle, $filesize, ";")) !== false) {
if($firstRow) {
$aData = $data;
$firstRow = false;
} else {
for($i = 0;$i < count($data); $i++) {
$aData[$i][] = $data[$i];
}
}
}
fclose($handle);
}
so you will get an multidimensional array with first row of headers.

You can open the file using fopen() as usual, get each line by using fgets() and then simply explode it on each comma like this:
<?php
$handle = #fopen("/tmp/inputfile.txt", "r");
if ($handle)
{
while (($buffer = fgets($handle)) !== false)
{
$array=explode(",",$buffer);
print_r($array)
// You have your array at this point.
}
if (!feof($handle))
{
echo "Error: unexpected fgets() fail\n";
}
fclose($handle);
}
?>

Without one unnecessary for cicle :
$handle = fopen($name, "r");
$first_row = true;
$final_ata = array();
$headers = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
if($first_row) {
$headers = $data;
$first_row = false;
} else {
$final_ata[] = array_combine($headers, array_values($data));
}
}
echo '<pre>';
print_r($final_ata);die;
will give you result:
Array
(
[0] => Array
(
[column1] => value
[column2] => value
[column3] => value
)
[1] => Array
(
[column1] => value
[column2] => value
[column3] => value
)
[2] => Array
..............

This is a comma-separated value not exactly column-wise. If you have a comma in column value so it will also break your string.
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
while(($filesop = fgetcsv($handle, 100000, ",")) !== false){
$abc= $filesop[0];
$xyz= $filesop[1];
}

Related

Using str_replace function to replace multiple string of an array

I have a multidimensional array $arrResult1 imported from CSV file, I want to replace the multiple values in that array with different values. I have tried str_replace and it works for single replacement.
<?php
$File = 'charge1.csv';
$arrResult = array();
$handle = fopen($File,"r");
if(empty($handle) == false){
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult[] = $data;
}
fclose($handle);
}
$file = 'ActualCharge.csv';
$arrResult1 = array();
$handle = fopen($file,"r");
if(empty($handle) == false){
while(($values = fgetcsv($handle, 1000, ",")) !== FALSE){
$arrResult1[] = $values;
}
fclose($handle);
}
$newArray = array();
foreach($arrResult1 as $inner_array) {
$newArray[] = str_replace("$11.16","$14.00", $inner_array);
}
var_dump($newArray[6]);
But when I try to replace more values like this
$newArray[] = str_replace(array("$11.16","$14.00"),array("$12.16","$15.00"), $inner_array);
It does not work. I have total 16 values that need to be replaced. Can you please help and let me know what I am doing wrong here or if there is any other way to solve this. TIA
here are the links to both csv files
https://drive.google.com/open?id=15JXhljASiDaZAyF0I6vC5_vfvFWH5Ylo
https://drive.google.com/open?id=1XzbzE39sCVVi4Ox1uj36g0smZJ4X4kCv

PHP beginner - issues with associative arrays

I'm trying to take a file of id numbers and find the names associated with those numbers from a different file and print a csv in the form id,name.
The Def.csv file is in the form
1;128;34;64;Uppland,
2;0;36;128;Östergötland,
3;128;38;192;Småland,
WIth the first number being the ID and the last field the name.
The IDs.csv is just IDs in no specific order with a comma and new line. ie.
12, \n
Here's the (updated, bad) script:
<?php
$ID;
$names;
$both = array();
$row = 0;
echo ("1\n");
if (($handle = fopen("IDs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$ID[$row] = $data[0];
$row++;
//print_r($ID);
}
}
print_r($ID);
fclose($handle);
if (($handle = fopen("Defs.csv", "r+")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$Names = $data[4];
// DEBUG, works// echo "$Names";
}
}
fclose($handle);
for ($c = 0; $c < $row; $c++)
{
$Both[$ID[$c]] = $Names[$ID[$c]];
}
foreach ($Both as $key => $value)
{
echo "$key,$value\n";
}
?>
This is my current output
Array
(
[0] => 2
[1] => 3
[2] => 1
)
2,t
3,l
1,u
for the small test case here it should be 2,Östergötland 3,Småland and 1,Uppland

How to read single column multiple rows csv file as an array using php

I have requirement where my csv file has urls,which i need to read as an array.The csv file has single column having mutiple rows with no header.I am reading using the below code.But it was not returning the output what i needed.
$handle = fopen($this->local_temp_folder.$file, 'r');
if(!$handle)
{
Model_Log::error('Cannot open uploaded file.');
die('Cannot open uploaded file.');
}
while (($data = fgetcsv($handle)) !== FALSE)
{
$num = count($data);
for ($c=0; $c < $num; $c++) {
$url_array[$c] = $data[$c];
}
}
print_r($url_array);exit;
Array
(
[0] => http://www.test.com/Fo/Finder/Digital_C/
http://www.test.com/Fo/Finder/orders/HighD/R56/
)
But i want it like the array as follows
Array
(
[0] => http://www.test.com/Fo/Finder/Digital_C/
[1] => http://www.test.com/Fo/Finder/orders/HighD/R56/
)
I have checked the csv file with note pad.In notepad it was looking like this
http://www.test.com/Fo/Finder/Digital_C/http://www.test.com/Fo/Finder/orders/HighD/R56/
But when i open with excel it was showing in two rows.
$handle = fopen($this->local_temp_folder.$file, 'r');
if(!$handle)
{
Model_Log::error('Cannot open uploaded file.');
die('Cannot open uploaded file.');
}
while (($data = fgetcsv($handle)) !== FALSE)
{
$url_array[] = $data[0];
}
try this, but if you share your csv file it would better to help you.
function read($file){
$data = array();
$csv_file = $file['folder'] . $file['name'];
$csvfile = fopen($csv_file, 'r');
if(!feof($csvfile)){
$i = 0;
while (!feof($csvfile)) {
$csv_data[] = fgetcsv($csvfile, 1000, ",");
$data[] = array(
'column1' => !empty($csv_data[$i][0])?$csv_data[$i][0]:'empty',
'column2' => !empty($csv_data[$i][1])?$csv_data[$i][1]:'empty',
'column3' => !empty($csv_data[$i][2])?$csv_data[$i][2]:'empty',
'column4' => !empty($csv_data[$i][3])?$csv_data[$i][3]:'empty',
'column5' => !empty($csv_data[$i][4])?$csv_data[$i][4]:'empty'
);
$i++;
}
}
return $data;
}
$data = read(array('folder'=>'','name'=>'file.csv'));//same folder
var_dump($data);

Edit first line CSV with PHP

I want to edit the first line (column titles) of an CSV file. Only one problem, the script I have is replacing everything. I've tried to search for a solution, but no luck.
Script:
<?php if(isset($_FILES["file"]["tmp_name"])){
$newCsvData = array();
if (($handle = fopen("".$_FILES["file"]["tmp_name"]."", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $base = array("EAN","article","status");
$replacements = array(1=> "SKU");
$basket = array_replace($base, $replacements);
$newCsvData[] = $basket;
}
fclose($handle);
}
$handle = fopen("export/".$_FILES["file"]["name"]."", "w");
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle); } else{ echo" ";} ?>
Does someone know what I'm doing wrong?
You should try:
$first = true;
while (($data = fgetcsv($handle, 1000, ",")) !== false) {
$base = array("EAN", "article", "status");
$replacements = array(1 => "SKU");
if($first){
$data = array_replace($base, $replacements);
$first = false;
}
$newCsvData[] = $data;
}
$first is a flag to detect just first row and replacing $data array values with titles array. Then you should push $data to $newCsvData. So only first row will replace by new values and other rows will remain as same data.

unable to write csv from array

I read most of the discussions about my problem but I do not find a solution.
So, I have a .csv file from which I read, extract all the content and populate a multidimensional array. That is the code I wrote to do that:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
After that, I extract the element I need and put it into another array. That array will be the content of the new .csv file.
This is the code:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
This is the "var_dump()" of the array:
Array(
[0] => Piemonte
[1] => maschi
[2] => 2005
[3] => 16.972)
etc.
I tried to put the content of the array $parserCsv using the method fputcsv(), with that script:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
but it did not work. The content of the file csvExtract.csv is blank. I do not understand my mistake, I tried other solution like create the array $parserCsv like:
$parserCsv = array(
array($region), array($sex), array($frequency), array($value));
and nothing change. Does anyone have some advise?
EDIT: Edited the code with the solution suggested by mkjasinski! The code is working now.
Thanks for all the replies.
Brus
Try this:
if (($handle = fopen("dateRegion.csv", "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$pr = 0;
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
# Count the total keys in the row.
$count = count($data);
# Populate the multidimensional array.
for ($x = 0; $x < $count; $x++) {
$brim[$pr][$x] = $data[$x];
}
$pr++;
}
fclose($handle);
}
and this:
$parserCsv = array();
$dip=1;
do {
$region = $brim[$dip][7];
$sex = $brim[$dip][8];
$frequency = $brim[$dip][9];
$value = $brim[$dip][10];
$parserCsv[] = array($region, $sex, $frequency, $value);
$dip++;
} while($dip <= 6336);
and save:
$fp = fopen('csvExtract.csv', 'w');
foreach ($parserCsv as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
are you getting some errors?
Is the file open in some other software? (like MS Excel?)
Following code enters 4 records in CSV
$parserCsv = array(
array('Piemonte'),
array('maschi'),
array(2005),
array(16.972)
);
$fp = fopen('blah.csv', 'w');
foreach($parserCsv as $fields)
{
fputcsv($fp, $fields);
}
fclose($fp);

Categories