fgetcsv convert array to string with double quote enclosure - php

I am getting data from a csv as an array using the fgetcsv function. I want to convert the array into a string, so I have used the implode function.
CODE:
if (($handle = fopen("storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
I am getting the result string say as Ter Aar, Netherlands,4.7159509,52.164688,,211316. But I would like each entry to be enclosed by double quotes. How can I do that?
Expected result: `"Ter Aar", "Netherlands","4.7159509","52.164688","","211316"
My approach #1 -
I passed the " as enclosure following the documentation but it is not working.
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
My approach #2 -
function convert( $str ) {
return '"'.$str.'"';
}
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
//$datafinal = array_map( convert, $data );
$datafinal = implode(",",$data);
echo $datafinal;
//var_dump($data);
}
fclose($handle);
}
This returns a string as "Ter Aar", "Netherlands","4.7159509","52.164688","","""211316".
As you can see the item following the blank data gets three quotes in the beginning.

You can do it as follows
// PHP 5.3 and later
echo $datafinal = implode(",",array_filter($data, function($value) { return $value !== ''; }));
This will help you sure
Thanks
Hope! It will help you

Try following code to read csv file and get data as multi-dimentional array
$csv_data = array_map('str_getcsv', file('../storelocations.csv'));
foreach ($csv_data as $key => $value)
{
var_dump($value); // print each row of csv
var_dump($value[0]) // print first column of each row
}

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 changing the index of multidimentional array to value of variable

Pretty new to PHP. I have a csv feed that i am trying to display every line of in the right place. The feed is loaded into a multidimentional array and I can echo out specific places like this.
echo $readcsv[0][2]
But I am trying to use the value of the variable $row in stead of the first number while doing a while loop.
Something like:
echo $readcsv[$row][2]
I have tried next(), str_replace() and strtr() but none of them seems to work while the loop is running.
$row = 1;
$readcsv = array();
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
$num = count($data);
echo $readcsv[$row][2];
$row++;
for ($c=0; $c < $num; $c++) {
}
$mycsvfile[] = $data;
}
fclose($handle);
}
CSV file:
title;image_link;link;empty;price;
1;back.gif;http://link.com;;19.95;
2;back.gif;http://link.com;;19.95;
3;back.gif;http://link.com;;19.95;
4;back.gif;http://link.com;;19.95;
5;back.gif;http://link.com;;19.95;
I am not quite sure from your code and question exactly what you are trying to do, but maybe its something like this
if (($handle = fopen("file.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
// you load the line into $data and its a one dimentional array
// occurance 2 is the `link` (http://link.com) if that what you want to echo
echo $data[2];
// as you have a loop, maybe you were trying to
// echo each fields from the csv so you can do that like this
foreach ($data as $idx => $value) {
echo "Column $idx = $value";
}
$mycsvfile[] = $data;
}
fclose($handle);
}

Get string entry from textfile in php

I have a question. How can i get a string from a entry in a textfile.
The texfile looks like:
Blabla2|123456
Blablablabla4|475387638
Blab1|387549900
Now i want to get from Blablablabla4 the number behind the |
Whats the read file function for it?
You can create a custom function, if you need that value often with different keys.
function getValueFromFile($file, $key){
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
if($data[0] == $key){
fclose($handle);
return $data[1];
}
}
fclose($handle);
}
return false;
}
and simply call it like:
echo getValueFromFile("your file name", "Blablablabla4");
Load each line of file to $line and then use function explode('|', $line_variable) for separating a string from int.
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = explode('|', $line);
$string = $line[0];
}
fclose($handle);
} else {
// error opening the file.
}

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.

read contents of two csv files in php and merge them into a third file based on a key field

I've searched the web and looked through existing answers but cant find a solution to this one. I want to use php to do the following task. Here are my files:
csv file 1: member.csv
member1|john|smith|2009
member2|adam|jones|2007
member3|susie|rose|2002
csv file 2: classes.csv
member1|massage|swimming|weights
member2|gym|track|pilates
member3|yoga|running|stretches
I want to output a third file called file3.csv which merges the two above files together based on the key field which is the member number. the output should be like this:
member1|john|smith|2009|massage|swimming|weights
member2|adam|jones|2007|gym|track|pilates
member3|susie|rose|2002|yoga|running|stretches
the delimiter is a bar character. I want to do this just using php - no other languages.
I would be very greatful for a solution.
Matt
Read both files and store data to the array with keys: member1, ...
Write a new file lines in loop:
foreach ($firstArray as $key => $value1) {
$value2 = $secondArray[$key];
// ...
}
<?php
$data = array();
if (($handle = fopen('file1.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = $line;
}
fclose($handle);
}
if (($handle = fopen('file2.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = array_merge($data[$memberId], $line);
}
fclose($handle);
}
ksort($data); // not needed, but puts records in order by member
if (($handle = fopen('file3.csv', 'w')) !== FALSE) {
foreach($data as $key => $value) {
fwrite($handle, "$key|" . implode('|', $value) . "\n");
}
fclose($handle);
}
Try this. It is untested.
$arr_one = array();
if (($fp = fopen("member.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_one[$data[0]] = $data;
}
fclose($fp);
}
$arr_two = array();
if (($fp = fopen("classes.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_two[$data[0]] = $data;
}
fclose($fp);
}
$classes_field_count = sizeof(current($arr_two));
$members = array_keys($arr_one);
foreach ($members as $key) {
if (!isset($arr_two[$key])) {
$arr_two[$key] = range(0, ($classes_field_count - 1));
}
unset($arr_two[$key][0]);
$result_arr[$key] = array_merge($arr_one[$key], $arr_two[$key]);
}
if (($fp = fopen("file3.csv", "w")) !== FALSE) {
foreach ($result_arr as $fields) {
fputcsv($fp, $fields, '|');
}
fclose($fp);
}

Categories