I am trying to make a PHP script that reads each row of a .csv file. I want to treat each row as an array of data. Please suggest how I can achieve the above?
Use the function fgetcsv().
// Read the first line, headers
$headers = fgetcsv($file);
// Now $headers is an array of your headers
// Read the lines one by one
while (false != ($line = fgetcsv($file))) {
// $line is an array of your cells
}
You could use the following to create an array from the csv;
$aArray = str_getcsv ( file_get_contents("/path/to/file.csv") , ',', '"', "\\");
var_dump($aArray);
Have a read of the PHP manual;
str_getcsv() and file_get_contents()
You can use following to read row from csv file and create array from the csv file:
<?php
$file = fopen("/path/to/file.csv","r");
$arrayCsv = array();
while(!feof($file)) {
$fpTotal = fgetcsv($file);
array_push($arrayCsv,$fpTotal);
}
fclose($file);
print_r($arrayCsv); //prints array from csv
?>
You can use the fgetcsv function to read data from a csv file. Please, look at this :
http://php.net/manual/en/function.fgetcsv.php
Related
I am trying to export a csv file with php, using an array returned by pg_fetch_array. But the csv file is empty.
If I write an array by hand, the csv is correct.
I tried to build an array from pg_fetch_all without success.
<?php
$listope = pg_fetch_array($marequete) ;
$fichier = fopen("export.csv", "w") ;
foreach ($listope as $line) {
fputcsv($fichier, explode(',',$line));
}
fclose($fichier) ;
?>
I know that the problem is the $listope var which does not return a proper array but I can't find the solution.
Thanks for help
Dont explode the array, the fputcsv() function does all that for you
So simply do
fputcsv($fichier, $line);
Another thing, you only read one row from the result set, now that maybe because you only expect one row, but as you also code a loop, if the query would generate more than one row try this, using pg_fetch_all()
$listope = pg_fetch_all($marequete) ;
$fichier = fopen("export.csv", "w") ;
foreach ($listope as $line) {
fputcsv($fichier, $line);
}
fclose($fichier) ;
Reference The manual
I think you are making this more complicated than necessary. pg_fetch_array() returns one row from your result-set, so it you want to save that in a csv file, you would only need:
$listope = pg_fetch_array($marequete) ;
$fichier = fopen("export.csv", "w") ;
fputcsv($fichier, $listope);
I have a csv file that looks something like this (there are many more rows):
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
What I want to do is to change all the values in the fourth column,456,343 to 500.
I'm new to php and am not sure how to do this.
I have tried
<?php
$file = fopen('myfile.csv', 'r+');
$toBoot = array();
while ($data = fgetcsv($file)) {
echo $data[3];
$data[3] = str_replace($data[3],'500');
array_push($toBoot, $data);
}
//print_r($toBoot);
echo $toBoot[0][3];
fputcsv($file, $toBoot);
fclose($file)
?>
But it prints
Jim,jim#email.com,8882,456
Bob,bob#email.com,8882,343
Array,Array
not
Jim,jim#email.com,8882,500
Bob,bob#email.com,8882,500
I've looked at this post, PHP replace data only in one column of csv but it doesn't seem to work.
Any help appreciated. Thanks
You can use preg_replace and replace all values at once and not loop each line of the CSV file.
Two lines of code is all that is needed.
$csv = file_get_contents($path);
file_put_contents($path, preg_replace("/(.*),\d+/", "$1,500", $csv));
Where $path is the path and to the CSV file.
You can see it in action here: https://3v4l.org/Mc3Pm
A quick and dirty way to way to solve your problem would be:
foreach (file("old_file.csv") as $line)
{
$new_line = preg_replace('/^(.*),[\d]+/', "$1,500", $line);
file_put_contents("new_file.csv", $new_line, FILE_APPEND);
}
To change one field of the CSV, just assign to that array element, you don't need to use any kind of replace function.
$data[3] = "500";
fputcsv() is used to write one line to a CSV file, not the entire file at once. You need to call it in a loop. You also need to go back to the beginning of the file and remove the old contents.
fseek($file, 0);
ftruncate($file, 0);
foreach ($toBoot as $row) {
fputcsv($file, $row);
}
I have json file which contains multiple json objects.
Example
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
Want to read this file and store into database, but I couldn't convert json to php array which further I can store into database.
I tried json_decode function, but its not working. I search for this but in every link its showing use json_decode. Below is my code
$filename = "folder/filename.json";
$data = file_get_contents($filename);
echo $data;
$tags = json_decode($data, true);
echo"<pre>";print_r($tags);exit;
$data is echoed but not the $tags.
Thanks in advance.
Make array of objects and use it later
$j = array_map('json_decode', file('php://stdin'));
print_r($j);
demo
If it's only four lines you can explode and json_decode each line and add it to an array.
$s = '{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}';
$arr = explode(PHP_EOL, $s);
Foreach($arr as $line){
$json[] = json_decode($line,true);
}
Var_dump($json);
https://3v4l.org/97m0E
Multiple objects in a row should be enclosed in a json array and separated with comma like elements.So you need a [ ] at the start and end of the file.Also you could close the pre tag
Either you should fix the file generating that 'json' or you can use fgets to get one line at a time, and use json decode on every line
As pointed by other, JSON which you shared isn't valid. And, I think, it is stored in your file in same fashion. I would suggest to read this file line by line each line then you can decode.
$handle = fopen("folder/filename.json", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$tags = json_decode($line, true);
echo"<pre>";print_r($tags);exit;
}
fclose($handle);
} else {
// error opening the file.
}
Assuming a file called `filename.json` contains the following lines
{"t":"abc-1","d":"2017-12-29 12:42:53"}
{"t":"abc-2","d":"2017-12-29 12:43:05"}
{"t":"abc-3","d":"2017-12-30 14:42:09"}
{"t":"code-4","d":"2017-12-30 14:42:20"}
So each one is a separate json entity
$filename = "folder/filename.json";
$lines=file( $filename );
foreach( $lines as $line ){
$obj=json_decode( $line );
$t=$obj->t;
$d=$obj->d;
/* do something with constituent pieces */
echo $d,$t,'<br />';
}
Your JSON is invalid, as it has multiple root elements
Fixing it like the following should work (note the [, ] and commas):
[
{"t":"abc-1","d":"2017-12-29 12:42:53"},
{"t":"abc-2","d":"2017-12-29 12:43:05"},
{"t":"abc-3","d":"2017-12-30 14:42:09"},
{"t":"code-4","d":"2017-12-30 14:42:20"}
]
If you cannot influence how the JSON file is created, you will need to create your own reader, as PHP is not built to support invalid formatting. You could separate the file by new lines and parse each one individually.
I have a working system on which I get the data of two .csv file. And save all the data into array and then compare some of the data existing on both csv file. The system works well but later I found out that some of the rows doesn't display on the array. I think I don't use the proper code in reading a csv file. I want to edit/improve the system. This is my code on reading or getting the data from csv file.
$thedata = array();
$data = file("upload/payment.csv");
foreach ($data as $deposit){
$depositarray = explode(",", $deposit);
$depositlist = $depositarray;
$key = md5($depositlist[9] . $depositlist[10]);
$thedata[$key]['payment'] = array(
'name' => $depositlist[0],
'email' => $depositlist[1],
'modeofpayment' =>$depositlist[8],
'depositdate' => $depositlist[9],
'depositamount' => number_format($depositlist[10],2)
);
}
'<pre>',print_r($thedata),'</pre>';
//more code here for comaparing of datas...
1.) What is wrong with file("upload/payment.csv") when reading csv file?
2.) What is the best code in reading a csv file that is applicable on the
system, not changing the whole code. Should remain the foreach loop.
3.) Is fgetcsv much better for the existing code? What changes should be made?
Yes, You can use "fgetcsv" for this purpose.
The fgetcsv() function parses a line from an open file.This function returns the CSV fields in an array on success, or FALSE on failure and EOF.
check the examples given below
eg1 :
<?php
$file = fopen("contacts.csv","r");
print_r(fgetcsv($file));
fclose($file);
?>
eg 2:
<?php
$file = fopen("contacts.csv","r");
while(! feof($file))
{
print_r(fgetcsv($file));
}
fclose($file);
?>
Link : https://gist.github.com/jaywilliams/385876
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to extract data from csv file in php
I have some data in XLS, I save them as CSV, the delimiter is **comma*.
Then I am trying to load the data from this CSV file:
$input = explode("\r\n", fread($file, filesize("my_data.csv")));
print_r($input);
The output:
Array ( [0] => data from the CSV file)
This is the problem - in the array is always just one item, where are printed out all data from the CSV file. How is that possible? Why isn't in the array as much items as is rows in the CSV file?
Also, I've tried to change "\r\n" for "\n", but it's the same.
What I am trying to do - load each line from the CSV file and this each line to process.
EXAMPLE OF THE FILE:
a,b,c,d
e,f,g,h
OUTPUT:
a,b,c,d e,f,g,h
I'd recommend using php's built in csv file reading function fgetcsv() and not create your own: http://php.net/manual/en/function.fgetcsv.php
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$row = implode (",",$data); //puts back together the row from the csv
echo $row. "\n"; //assuming you want a visual linebreak on console, add the \n
}
fclose($handle);
}
How I solved this issue:
In the XLS file, before exporting the file into CSV, I added in the end of sheet one more column with the char '.