I am writing a PHP script that imports a csv and inserts into a table but i need to get the first row so i can have the field names..here is my csv
id artist song
11 NewBee great stuff
10 anotherNewbee even better
6 NewArtist New song
As you can see the first row is the name of the fields that i need. here is my loop
$handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r');
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
print_r($data);
//do something with it but i need the first time around
array(3) { [0]=> string(2) "id" [1]=> string(6) "artist" [2]=> string(4) "song" }
array(3) { [0]=> string(2) "11" [1]=> string(6) "NewBee" [2]=> string(1) "great stuff" }
array(3) { [0]=> string(2) "10" [1]=> string(13) "anotherNewbee" [2]=> string(1) "even better"}
How do i get the first and put them in variables and continue the loop of the data using those fields in an insert statement
Would this work for you?
$row = 1;
while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
if($row == 1) {
// do something
}
else
{
// do something
}
++$row;
}
Prior to your while block, just run the fgetcsv function a single time and store the field headings.
Either deepsat's or mattmoon9's methods will work fine. Here's what mattmoon9's answer would look like structured in code (also based on my comment on the answer):
$handle = fopen('csvs/'.$_FILES["csv"]["name"], 'r');
if (($columns = fgetcsv($handle, 1000, ',')) !== false) {
while (($data = fgetcsv($handle, 1000, ',')) !== false) {
// Process data
}
// Insert into database using $columns as table column names
} else {
// The file couldn't be parsed as CSV
}
Related
My query gives me a result in an array :
$donnnes =
Table ( [0] => Table ( [sku_code] => A1101_0090_TU [SKU_EAN] => 9346799868270 ) )
My .txt file create itself well but fills up like this :
MMXC1_|9346799868270|0|0
MMXC1_| |0|1
MMXC1_| |1|4
...
Only the first line is completely filled, in the others there is nothing between the two pipes '|' after "MMXC1_" while in my var_dump($data_final); all the data is there, where does my error come from?
$resultat = mysqli_query($bdd, "SELECT trim(concat(concat(SKU_ITEM_VARIANT,'_'),trim(SKU_SIZE)))as sku_code , SKU_EAN FROM dwh_dev.dwh_d_sku");
while ($donnees[] = mysqli_fetch_assoc($resultat)) {
}
print_r($donnees); //Array ( [0] => Array ( [sku_code] => A1101_0090_TU [SKU_EAN] => 9346799868270 )
$constante = "MMXC1_";
$temp2 = array_column($donnees, 'SKU_EAN', 'sku_code');
if (($handle = fopen("$nomcsv", "r")) !== FALSE) {
$firstLine = true;
while (($data = fgetcsv($handle, 1000000, ";")) !== FALSE)
{
if(!$firstLine) {
$SKU_EAN = $temp2[$data[6].'_'.$data[7].'_'.$data[8]];
var_dump($SKU_EAN); //A1101_0090_TU A1104_0090_TU
// Create line here and immediately add it to `$data_final`
$data_final[] = $constante.'|'.$SKU_EAN.'|'.$data[12].'|'.$data[13];
var_dump($data_final); // array(1) { ["A1101_0090_TU"]=> string(13) "9346799868270" } array(1) { [0]=> string(26) "MMXC1_|9346799868270|0|0" } array(2) { [0]=> string(26) "MMXC1_|9346799868270|0|0" [1]=> string(13) "MMXC1_||0|0" }
}
$firstLine = false;
}
}
$cheminfile = "//alcyons/IT/PhotoShoot/retail/CSV/TXT_Finaux/MMX".date('His').".txt";
$fp = fopen("$cheminfile", "w");
fputcsv($fp, $data_final, "\n");
fclose($fp);
Why are you using fputcsv on a .txt file? use fwrite instead.
replace
fputcsv($fp, $data_final, "\n");
with
foreach($data_final as $data){
fwrite($fp,$data."\n");
}
So, I got a CSV file that I correctly import in PHP.
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;
}
echo '<pre>';
$product_csv = csv_to_array("$underfolder/$value");
print_r($product_csv);
echo '</pre>';
This works and give show as result:
Array (
[0] => Array
(
[Name] => product name xyz
[Description] => der trefa a as sadfse
[TAGS] => tag1 tag2 tag3
[360] => yes
[VR] => no
)
)
But how I echo a VALUE of $product_csv? Like if I want to print out "product name xyz"? I tried with echo $product_csv["0"]['Name'] but without any results...
var_dump(array_keys($product_csv[0])); gives me:
array(5) { [0]=> string(7) "Name" [1]=> string(11) "Description" [2]=> string(4) "TAGS" [3]=> int(360) [4]=> string(2) "VR" }
As you can see in your var_dump(array_keys($product_csv[0])); output: string(7) "Name", there must be 3 invisible characters as Name is only 4 characters not 7.
Attempt to trim them by replacing:
$header = $row;
With:
$header = array_map('trim', $row);
It could very well be a Byte Order Mark (BOM). If you are creating this file then check the editor to see if it saves it with a BOM, and if possible disable it.
I've got this nice script with a lot of help working:
if (isset($_POST['talente'])) { // array(2) { [0]=> string(1) "2" [1]=> string(1) "3" }
$talente = $_POST['talente'];
$myFile = fopen("talente.csv", "r"); // e.f.: name;1;-;stuff
$csv = [];
while ($data = fgetcsv($myFile, 1000, ";")) {
$csv[] = $data;
}
fclose($myFile);
$i = 0;
$talentline = array_filter($csv, function($i) use ($talente) {
return in_array($i, $talente--);
}, ARRAY_FILTER_USE_KEY);
$talentline = array_filter($talentline);
$talentline = array_values($talentline);
}
$talentline[0][0] = isset($talentline[0][0]) ? $talentline[0][0] : "";
...
This works very well on my PC in localhost. But after uploading it on my host nothing happened. After printing and dumping a while I noticed, that every variable has the expected value/s but $talentline. When I set var_dump around it, it gives me a multi-dimensional array back as I expect it on PC. But on my Hoster only NULL. I couldn't find out why.
I am trying to split an array if one of the lines has an empty value. My array is being exported to a csv and has multiple lines of data, if the data is not complete it will be sent to a uncomplete csv and if it is complete it will be sent a complete csv.
This is what my array structure looks like the blank field on the first line is on email (this line should be split out of the array:
array(2) {
[0]=> array(6) {
["Username"]=> string(47) " STARRY NIGHT CINEMA - RISE OF THE GUARDIANS "
["Email"]=> string(0) ""
["Location"]=> string(1) "1"
["Type"]=> int(1)
["Title"]=> string(47) " STARRY NIGHT CINEMA - RISE OF THE GUARDIANS "
["Description"]=> string(491) "the Tooth Fairy"
}
[1]=> array(6) {
["Username"]=> string(26) "Maui Nui Botanical Gardens"
["Email"]=> string(18) "info#mnbg.org"
["Location"]=> string(1) "1"
["Type"]=> int(1)
["Title"]=> string(26) "Maui Nui Botanical Gardens"
["Description"]=> string(50) "Conserving Hawaiian Plants & Cultural Heritage"
}
}
Writing to my csv:
$fp = fopen('entries.csv', 'w');
foreach ($entries as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
if (!copy("http://www.simonstaton.co.uk/entries.csv", "entries.csv")) {
echo ("failed to copy file");
};
I have no idea where to start with this and as to what function I should use so any advice is greatly appreciated.
Simon
To separate the entries by complete or incomplete you can open two files for writing. One to contain each.
// filenames
$fn_complete = 'entries.csv';
$fn_incomplete = 'incomplete_entries.csv';
// file pointers
$fp_complete = fopen($fn_complete, 'w');
$fp_incomplete = fopen($fn_incomplete, 'w');
// write CSVs
foreach ($entries as $fields) {
if (in_array('', $fields))
fputcsv($fp_incomplete, $fields);
else
fputcsv($fp_complete, $fields);
}
fclose($fp_complete);
fclose($fp_incomplete);
if (!copy('http://www.simonstaton.co.uk/' . $fn_complete, $fn_complete)) {
echo ('failed to copy file ' . $fn_complete);
};
if (!copy('http://www.simonstaton.co.uk/' . $fn_incomplete, $fn_incomplete)) {
echo ('failed to copy file ' . $fn_incomplete);
};
You can check if any of the values in your array is empty like this:
in_array('', $array)
so it then you can do a simple if
if(in_array('', $array)) {
//Do whatever you have to do to slip your array. I don't understand exactly what you want the end result to look like .
}
First pack your CSV data into an array using fgetcsv(). Then use a loop to search for "".
Exemplar:
$row = 1;
if (($resource = fopen("example.csv", "r")) !== false) {
while (($data = fgetcsv($resource, 1000, ",")) !== false) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
if ($data[$c] == "") {
// operate
}
}
}
fclose($handle);
}
By the way, don't use the split() function. Use preg_split().
http://php.net/manual/en/function.fputcsv.php
I want to make a array out of a csv file with the header as key. But when I insert the script into a database than it overrides the previous row of the csv file and only the last value gets stored in the database.
I think its because the array has a default value of 5. How can I change the value so that it creates a new value?
This is the script
<?php
// open the file.
if (($handle = fopen("test2.csv", "r")) !== FALSE) {
// read the column headers in an array.
$head = fgetcsv($handle, 1000, ";");
// read the actual data.
while (($data = fgetcsv($handle, 1000, ";")) !== FALSE) {
// create a new array with the elements in $head as keys
// and elements in array $data as values.
$combined = array_combine($head,$data);
// print.
var_dump($combined);
}
// done using the file..close it,
}
?>
this is the output
array(5) { ["name"]=> string(5) "Harry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
array(5) { ["name"]=> string(5) "Gerry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
array(5) { ["name"]=> string(5) "merry" ["description"]=> string(4) "test" ["offer_url"]=> string(42) "demo.com/admin/offers/add" ["preview_url"]=> string(42) "demo.com/admin/offers/add" ["expiration_date"]=> string(9) "23-8-2013" }
you must go through multidimensional array and add additional index to the combined param like this - combined[]=...:
// create a new array with the elements in $head as keys
// and elements in array $data as values.
$combined[] = array_combine($head,$data);