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
Related
I have simple csv file:
id | ean
1 | 2342342345234
2 | 3453453454353
I want to have access for this data by variable in foreach loop:
$id = 1, $ean = 2342342345234
Is that possible?
<?php
$row = 1;
if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Your delimiter is a pipe, not a comma so change the third parameter of your fgetcsv. You can then assign the values statically if you are using the values in current iteration, or use an array for later storage.
$row = 1;
if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, "|")) !== FALSE) {
$id = $data[0];
$ean = $data[1];
...
or array:
$row = 1;
if (($handle = fopen("upload/products.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 10000, "|")) !== FALSE) {
$ids[] = $data[0];
$eans[] = $data[1];
then use the foreach with the key to access appropriate pairings.
foreach($ids as $key => $id) {
echo $id . ' ' . $eans[$key];
}
Here is some sample code to create an associative array.
$lines = explode( "\n", file_get_contents( 'input.csv' ) );
$headers = str_getcsv( array_shift( $lines ) );
$data = array();
foreach ( $lines as $line ) {
$row = array();
foreach ( str_getcsv( $line ) as $key => $field )
$row[ $headers[ $key ] ] = $field;
$row = array_filter( $row );
$data[] = $row;
}
I've got a csv file which contains product datas and prices from two distributors.
There are 67 keys in this file.
Now I want to search all EANs in this file which are twice available and then get the cheapest price.
After that delete the other higher price product line.
The CSV has a key for my merchant.
I made a test csv for easier view:
artno;name;ean;price;merchant
1;ipad;1654213154;499.00;merchant1
809;ipad;1654213154;439.00;merchant2
23;iphone;16777713154;899.00;merchant2
90;iphone;16777713154;799.00;merchant1
After the script runs through, the csv should look like (writing to new file):
artno;name;ean;price;merchant
809;ipad;1654213154;439.00;merchant2
90;iphone;16777713154;799.00;merchant1
I played around with fgetcsv, looping through the csv is not a problem, but how I can search for the ean in key 2?
$filename = './test.csv';
$file = fopen($filename, 'r');
$fileline = 1;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($fileline == "1"){ $fileline++; continue; }
$search = $data[2];
$lines = file('./test.csv');
$line_number = false;
$count = 0;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key : $line_number;
$count++;
}
if($count > 2){
echo "<pre>",print_r(str_getcsv($lines[$line_number], ";")),"</pre>";
}
}
I think this is what you are looking for:
<?php
$filename = './test.csv';
$file = fopen($filename, 'r');
$lines = file('./test.csv');
$headerArr = str_getcsv($lines[0], ";");
$finalrawData = [];
$cheapeastPriceByProduct = [];
$dataCounter = 0;
while (($data = fgetcsv($file, 0, ";")) !== FALSE) {
if($dataCounter > 0) {
$raw = str_getcsv($lines[$dataCounter], ";");
$tempArr = [];
foreach( $raw as $key => $val) {
$tempArr[$headerArr[$key]] = $val;
}
$finalrawData[] = $tempArr;
}
$dataCounter++;
}
foreach($finalrawData as $idx => $dataRow ) {
if(!isset($cheapeastPriceByProduct[$dataRow['name']])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
else {
if(((int)$dataRow['price'])< ((int)$cheapeastPriceByProduct[$dataRow['name']]['price'])) {
$cheapeastPriceByProduct[$dataRow['name']] = $dataRow;
}
}
}
echo "<pre>";
print_r($finalrawData);
print_r($cheapeastPriceByProduct);
I just added $finalData data array to store the parsed data and associated all rows with their header key counterpart then you can compare and filter data based on your criteria.
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);
}
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];
}
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.