How to read each field into an array properly? - php

I have this structure in a csv file
"http://example.com/example.jpg","example","example2","example3","1234,56"
Now I assign this line to a variable $line and
$fields = explode('","',$line);
It stops at "http". The same with
$fields = csv2array(str_replace(':','\\:',$line),$delimiter=',',$enclosure='"',$escape='\\');
where
function csv2array($input,$delimiter=',',$enclosure='"',$escape='\\'){
$fields=explode($enclosure.$delimiter.$enclosure,substr($input,1,-1));
foreach ($fields as $key=>$value)
$fields[$key]=str_replace($escape.$enclosure,$enclosure,$value);
return($fields);
}
How to read each field into an array?

I would suggest reading the file using fgetcsv() which returns an array of values exactly as you want.

Related

Use array for array push instead of a string

I'm using the following code:
$patients_with_site = [];
if (in_array($zip_code, $current_zip_codes)) {
echo "The referral id is: ".$referral_id;
array_push($patients_with_site,$referral_id);
print_r($patients_with_site);
}
I'm then trying to push it to a CSV file with this code:
$fp = fopen('patients_with_site.csv', 'w');
foreach ($patients_with_site as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
I'm getting an error saying that the $patients_with_site is a string and fputcsv requires an array.
If fputcsv requires array - provide array:
foreach ($patients_with_site as $fields) {
fputcsv($fp, [$fields]);
}
And yes, every value of $patients_with_site is a string and not array.
Your $patients_with_site's elements are strings.
The second argument of fputcsv must be an array, so unless you have a multidimensional array for $patients_with_site you shouldn't loop through it.
So it should work if you only call fputcsv($fp, $patients_with_site).
See PHP fputcsv

Return row from an array if contains a value from another array with a different value format

I need to compare 2 different format arrays. The goal is to print from file1 only that rows which contain value from file2.
I suppose that I have to load both files into 2 arrays and compare it. I tried array_intersect(), in_array() and array_key_exists(), nothing works for me.
Here is the example of data files:
File 1:
2.26.81.0,4,10146128,10165054
82.132.227.75,7,10146130,10166530,10166093
91.206.0.35,10,10150898,10165809
88.145.18.102,3,10169097,10141126,21729395
File 2:
10146128
10146130
Result should looks like this:
2.26.81.0,4,10146128,10165054
82.132.227.75,7,10146130,10166530,10166093
I have loaded both files in 2 arrays and I need to compare them now
$bought = fopen('f_data.csv', 'r');
$visited = fopen('l_data.csv', 'r');
$line = fgets($bought);
while(! feof($bought)) {
$line = fgets($bought);
$bought_f[] = $line;
}
$line2 = fgets($visited);
while(! feof($visited)) {
$line2 = fgets($visited);
$visited_f[] = $line2;
}
The functions you used didn't work because you converted the first file in an array putting each line into an array element, but since each line not a value but a list of values you should create a two-dimensional array (an array of arrays), so each array element contains just a value. For example you can do that using file() and explode():
// getting an array with an element for each line
$file1=file("file1.csv");
$length=count($file1);
// converting each line in an array of the comma-separated values
for ($i=0;$i<$length;$i++) {
$file1[$i]=explode(",",$file1[$i]);
}
//for file2 using file() is enough as each line only contains one value
$file2=file("file2.csv");
In this way $file1[0][0] is2.26.81.0, $file1[0][1] is 4, $file1[0][2] is 10146128 and so on. Then, you have several options, the most basic one is using a double loop:
foreach ($file1 as $line) {
foreach ($file2 as $value) {
// code for checking if $value is contained in $line and store/print the result
}
}
Depending of what you need using in_array() for comparison and implode() for converting the line back to a comma-separated string would do the job.
Also note that if the first file can contain several values of the second file in the same line you can get duplicate results, in that case the solution would be stop checking the values of the second array as soon as you get a match.

How to get value by column name in php spreadsheet-parser library?

I'm using akeneo-labs spreadsheet-parser library to extract data from xlsx file.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
var_dump($rowIndex, $values);
}
Actually, you can get value by column index in a loop, is it possible to get value by column name instead?
maybe using another package as suggested fixes your problem.
also you can use array_column https://www.php.net/manual/en/function.array-column.php
Maybe you can do that in a spreadsheet CSV file by using PHP default function fgetcsv(), you can go throw an overview from here: https://www.php.net/manual/en/function.fgetcsv
fgetcsv — Gets line from file pointer and parse for CSV fields
First of all, save as your Xls file in CSV type then you can take your value from that CSV file by column name.
You can try this.
use Akeneo\Component\SpreadsheetParser\SpreadsheetParser;
$workbook = SpreadsheetParser::open('myfile.xlsx');
$myWorksheetIndex = $workbook->getWorksheetIndex('myworksheet');
// all columns
$columns = [];
foreach ($workbook->createRowIterator($myWorksheetIndex) as $rowIndex => $values) {
if ($rowIndex == 1) {
$columns = $values;
} else {
$datum = array_combine($columns, $values);
// get value by column name
var_dump($datum['name']);
}
}

PHP parse CSV by columns

I would like to ask for help with this task: I have CSV for example like this:
column1$column2$column3
123$xyz$321
456$zyx$654
And I would like to parse it by PHP to Arrays by columns / headers -> for example
$column1 = {123,456}
$column2 = {xyz,zyx}
$column3 = {321,654}
Thanks everyone.
Consider the following code and explanations:
$file = file("example.csv"); // read the file to an array
$cols = array();
for ($i=1;$i<count($file);$i++) { // loop over $file,
// starting in the second line
$row = explode('$', $file[$i]); // make an array with explode
for ($j=0;$j<count($row);$j++) // loop over the $row array
array_push($cols["column".$j], $row[$j]);
// push it to the cols array
}
print_r($cols);
What are your curly brackets supposed to do? In PHP an array is formed with [].
Rather than reading the whole file to an array you could as well read each line and push it to the cols array.

PHP, problem with str_replace while reading from array

i am new to php, and i am trying to do a script that reads an CSV file(file1.csv) and compare the words in the file with words in a html file (file2.html), if word in file2.html match with the key part in file1.csv it should change the file2.html contents with the value of the key matched ..
what i have done so far is this :
$glossArray = array();
$file_handle = fopen("file1.csv", "r");
while (!feof($file_handle) ) {
$line_of_text = fgetcsv($file_handle, 10000,';');
$glossArray[$line_of_text[0]] = $line_of_text[1];
$counter++;
}
fclose($file_handle);
$file = file_get_contents("file2.html");
foreach($glossArray as $key => $value){
$results = str_replace($key," means ".$value ,$file);
}
echo $results;
i think that my problem occurs when i try to iterate and change values .. because what i see is only the contents of file2.html unchanged
any help would be appreciated
thank you in advance
Nader
P.s. i edited the old code with the new one after your valuable advise .. now it's like this .. but still doesnt work.
Update: changing the foreach with :
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
solved the problem .. but another one comes up: now every time it replaces a string it adds the word 'Array' ahead of it.
You're passing the entire $glossArray in to str_replace each time. You're also passing the initial file contents in each time you do str_replace, so at most you'd see one replacement. I think you want to change to something like this:
$results = $file;
foreach($glossArray as $index=>$value)
{
$results = str_replace($index,$value ,$results);
}
Since str_replace allows arrays for the first two parameters (as another user mentions) you could also do something like this instead of a loop:
$results = str_replace(array_keys($glossArray), array_values($glossArray), $file);
Yes, the problem is in your second foreach. It should read like this:
foreach($glossArray as $key => $value){
$results = str_replace($key,$value ,$file);
}
You forgot the key, so it's replacing every instance of every value in $glossArray with the $value. Good luck with that!
Why are you opening file2.html for reading and writing, then grabbing the contents of it?
(BTW - this is going to go horribly wrong on a system with strict locking)
foreach($glossArray as $value)
{
$results = str_replace($glossArray,$value ,$file);
I think this should be
foreach($glossArray as $old=>$new)
{
$results = str_replace($old, $new, $file);
Although it would be a lot more efficient to load the pairs from the glossary into 2 seperate numbered arrays, then just call str_replace once.
Your first parameter for str_replace should not be $glossArray as that's an array and not the string to replace.
I assume that your CSV-file contains something like "SEARCH;REPLACE"? In that case, your foreach should look like this: foreach ($glossArray as $searchString => $value).
Then try
$file = str_replace($searchString, $value ,$file);
instead of
$results = str_replace($searchString, $value ,$file);
because right now you're overwriting $results again and again with every str_replace ... echo $file when you're done.
BTW: What's $counter doing?
The solution to your new problem (which should really be it's own question, not an edit of the existing one) is that array_values returns an array, and when you concatenate an array with a string, php inserts 'Array' instead of the value.
$results = str_replace(array_keys($glossArray), "means ".array_values($glossArray), $file);
is incorrect. You should do this instead:
$vals = array_values($glossArray);
foreach($vals as $k=>$v)$vals[$k] = 'means '.$v;
$results = str_replace(array_keys($glossArray), $vals, $file);
Notice that the values of glossArray are extracted, and each value concatenated with your string - if you just try and concatenate the string with the array, you'll get a string, not an aray.

Categories