Pipe Delimited CSV File to HTML (But Values have Commas) - php

I am in the process of turning this CSV File of quotes to a HTML Table. The CSV Table is formatted as such:
The old world is dying, and a new world struggles to be born; now is the time of monsters.|Antonio Gramsci|1891-1937
The unexamined life is not worth living.|Socrates|c.469-399 B.C.
When converting it to an array by
<?php
$file = fopen("quotes.csv", "r");
$data = fgetcsv($file, 1000, "|");
$arr = [];
while (($data = fgetcsv($file, 1000, "|")) !== false) {
$arr[] = $data;
}
echo "<pre>";print_r($arr)
?>
1st Row gives me
[0] => Array
(
[0] => The old world is dying, and a new world struggles to be born; now is the time of monsters.|Antonio Gramsci|1891-1937|
Whereas 2nd row Correctly Gives me this output
[1] => Array
(
[0] => The unexamined life is not worth living.
[1] => Socrates
[2] => c.469-399 B.C.
)
How can I make the first row give me the output of the 2nd row? I know it has something to do with that comma in the first column but how do I work around that?

Related

Converting scientific number read from excel into csv

I am having an issue while reading from the excel sheet. I am getting my barcode values in scientific format in csv.
How do i parse the original value instead of the scientific number ?
Example :
9,96E+12 [In excel]
9960000000000 [I want this in CSV]
I am using fgetcsv function in php to parse the csv file.
while (($row = fgetcsv($handle, 1000, ';')) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
Output that i am getting :
[0] => Array
(
[code] => FJT8-thr-thrtC2-VSXL
[barcode] => 9960000000000
[amount] => 70
[status] => 1
)
I want the output as
[0] => Array
(
[code] => FJT8-thr-thrtC2-VSXL
[barcode] => 9,96E+12
[amount] => 70
[status] => 1
)
You can use the floatval() and sprintf function to convert it back and forth as long as you convert the "," to "." before you use the number in PHP.
<?php
$start = '9,96E+12';
$str = floatval(str_replace(',','.',$start));
// Proof of concept
echo $start."<br />"; // starting off with 9,96E+12
echo $str."<br />"; // Converted number is 9960000000000
echo sprintf('%.2e',$str); // back to scientific number 9.96e+12
?>

Escaping a comma when uploading a .csv to a database with PHP

I'm trying to do a simple PHP function to put a .csv file into a database. The problem is that the files are delimited with a semicolon and for some reason when a cell contains a comma it leaves out everything after it.
For example the .csv file
manufacturer;comment;year
toyota;good car, bad color;1997
comes out as the following when printed with the print_r() function
[0] => Array
(
[0] => manufacturer
[1] => comment
[2] => year
)
[1] => Array
(
[0] => toyota
[1] => good car
)
Edit
Here's the code I'm using.
//get the contents of the .csv file
$filepath = './files/csvfile.csv'
$fileopen = fopen($filepath,"r");
//create an empty array
$csv = array();
//go through the .csv file with fgetcsv()
while(($line = fgetcsv($fileopen,";")) !== FALSE)
{
$line = explode(";",$line[0]);
$csv[] = $line;
}
//print the result
echo "<pre>";
print_r($csv);
echo "</pre>";
fclose($fileopen);
Put the delimiter as the 3rd argument
http://php.net/manual/en/function.fgetcsv.php
while(($line = fgetcsv($fileopen, 0, ";")) !== FALSE)
I don't think you need that explode line either.

multidimensional array search PHP reading from file

Hi In another post I learned how to read data from a text file into an array. After the script reads the text file here is the resulting array of data.
What I'm trying to do is simply return the 'key' or record number where a search string appears i.e. if I pass the parameter 'muscle3' it should return '3' because it is the third 'row' in the table
Then I can easily extract the other columns with $arrayTable[$keyVal][2] and $arrayTable[$keyVal][3]
As you can see the pageName which is the search field is stored in $arrayTable[$keyVal][2]
By getting the $keyValue from a search, i can then get the other pages.
i.e. mygreatwebsite.com/?page=muscle3
it then fetches the data from the array and it
But when I run the script below it gives the following error message
"Warning: Invalid argument supplied for foreach()"
$page=$_REQUEST['page'];
$keyVal = searchForId($page,$arrayTable); // this is the value I want returned
function searchForId($id, $array) {
foreach ($array as $key => $val) {
print_r ($val); print "<br><br>";
if ($val === $id) {
return $key;
}
}
return null;
here is the output from the above script
Array ( [0] => muscle1 [1] => arrayField [2] => description )
Array ( [0] => muscle2 [1] => arrayField2 [2] => description )
Array ( [0] => muscle3 [1] => arrayField3 [2] => description )
Can someone help me figure this one out? Thanks!
Someone asked how the array table is being defined: here it is
$i=0;
if (($handle = fopen($inputFile, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$arrayTable[$i] = $data; $i++;
}
fclose($handle);
}
input file is a CSV file with the first row containing column headings and each subsequent row containing data
the first column is called 'pageName'
What I'm seeking to do is 'search' for the 'pageName' and just return which record.
i.e. Muscle 1 is in record #1 muscle3 is is record #3
its a simple example - the CSV file is much more complex that this.

Covert comma delimited string to array like a csv string without using str_getcsv function

this could have been asked over and over again but i have failed to get the best answer allover google. Please help me.
Problem
Am fetching data from a forex rates rest API and this is exactly how the reply looks when i print it out.
EUR/USD,1380039070258,1.34,868,1.34,873,1.34641,1.35193,1.34932
USD/JPY,1380039068699,98.,789,98.,797,98.471,99.180,98.838
GBP/USD,1380039067482,1.60,082,1.60,095,1.59546,1.60500,1.60419
EUR/GBP,1380039067816,0.84,245,0.84,256,0.84067,0.84495,0.84127
USD/CHF,1380039064893,0.91,161,0.91,172,0.90974,0.91338,0.91097
EUR/JPY,1380039066371,133.,236,133.,252,132.697,134.008,133.371
EUR/CHF,1380039063317,1.22,951,1.22,966,1.22853,1.23050,1.22919
USD/CAD,1380039062062,1.02,960,1.02,969,1.02655,1.03111,1.02841
AUD/USD,1380039069019,0.93,957,0.93,968,0.93635,0.94329,0.94307
GBP/JPY,1380039066561,158.,149,158.,170,157.342,158.978,158.552
Note that each line contains comma delimited data and the next line is on the next line.
When i store this data in a response variable $resp and use the code below
$result=str_getcsv($resp, "\n");
pr($result);
I get the expected result as below
Array
(
[0] => EUR/USD,1380039070258,1.34,868,1.34,873,1.34641,1.35193,1.34932
[1] => USD/JPY,1380039068699,98.,789,98.,797,98.471,99.180,98.838
[2] => GBP/USD,1380039067482,1.60,082,1.60,095,1.59546,1.60500,1.60419
[3] => EUR/GBP,1380039067816,0.84,245,0.84,256,0.84067,0.84495,0.84127
[4] => USD/CHF,1380039064893,0.91,161,0.91,172,0.90974,0.91338,0.91097
[5] => EUR/JPY,1380039066371,133.,236,133.,252,132.697,134.008,133.371
[6] => EUR/CHF,1380039063317,1.22,951,1.22,966,1.22853,1.23050,1.22919
[7] => USD/CAD,1380039062062,1.02,960,1.02,969,1.02655,1.03111,1.02841
[8] => AUD/USD,1380039069019,0.93,957,0.93,968,0.93635,0.94329,0.94307
[9] => GBP/JPY,1380039066561,158.,149,158.,170,157.342,158.978,158.552
[10] =>
)
This works perfectly on my localhost server but when i deploy it, i get an error below
Call to undefined function str_getcsv()
It seams the server doesn't know about that str_getcsv() function i tried to use.
I tried to use other functions like fgetcsv() but cant get them to give me the array output i want.
below is how i used fgetcsv()
$fh = fopen('php://memory', 'rw');
fwrite($fh, $resp);
rewind($fh);
$result = fgetcsv( $fh, strlen($resp), ',', ' ');
fclose($fh);
pr($result);
but it picks only the first line of the $resp string and here is the output it gives
Array
(
[0] => EUR/USD
[1] => 1380040007538
[2] => 1.34
[3] => 882
[4] => 1.34
[5] => 890
[6] => 1.34641
[7] => 1.35193
[8] => 1.34932
)
yet i want all the lines of the $resp string indexed in the array like in the first array
Please if you can help me get this to work by converting the string to the desired array, thanks inadvance.
You can use explode("\n", $resp) to get array of lines.
People are right when they tell you to check the documentation or Google. Developing software is not just about typing code but also a good part of reading and research.
The error your server produces is very likely because you run an ancient php version and should update it - security is a keyword here as well. Because this function http://php.net/manual/en/function.str-getcsv.php is supported since 5.3.
Further the first comment there includes an example of how to archive the same thing without that function:
function csv_to_array($filename='', $delimiter=',')
{
if(!file_exists($filename) || !is_readable($filename))
return FALSE;
$header = NULL;
$data = array();
if (($handle = fopen($filename, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
return $data;
}
I have not tested it, that's your job.
The comment after that has an even more detailed replacement if the function is missing.

php csv to array

I am fairly new to php and got this from a stack overflow question and cant seem to get it to work for me.
<?php
if (($handle = fopen("fullbox.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
echo "<pre>".print_r($data)." <br /></pre>";
}
fclose($handle);
}
echo $data[1];
?>
I need to set up a couple arrays for pricing using a large number of products(which I can pull from my csv file) Fullbox.csv consists of just 10 numbers with 2 decial places. I have just been trying to test this and this is the output that I get:
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 5.00
)
Array
(
[0] => 2.50
)
Array
(
[0] => 6.48
)
Array
(
[0] => 3.99
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Array
(
[0] => 8.53
)
Array
(
[0] => 4.74
)
Why is the array setting all values in the [0} place holder of the array and also why is there a 1 in between each line. Thanks in advance.
Update If this is a ten item array this should then return the value of the 1 entry in the array but it doesn't. I essentially just need to store all of the prices so I can use them as variables later. I don't need them to be printed. Thanks again.
echo $data[1];
print_r does not return the formatted array by default; it outputs it and returns 1. Pass true as a second parameter.
echo "<pre>".print_r($data, true)." <br /></pre>";
All the values are in the 0 index of the array because arrays start at 0. There is nothing wrong there.
Try this:
$f = fopen(yourfile, "r");
$fs = filesize(yourfile);
$content = fread($f, $fs);
$lines = explode("\n", $content);
$result = array();
foreach($lines as $line) $result[] = explode(",", $line);
CSV as in Comma Seperated-Values is an array each line. So each line -even if it has only 1 value- is array.
Also you don't need to echo "print_r".
you also read the data from the CSV using the following function and sort using the usort() function.
http://www.pearlbells.co.uk/how-to-sort-a1a2-z9z10aa1aa2-az9az10-using-php/
Read data from the CSV
function readCSV() {
$csv = array_map('str_getcsv', file('data.csv'));
array_shift($csv); //remove headers
$csvData = splitandSort($csv);
createCSV($csvData);
}

Categories