2

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?

2
  • What problem in your script?? Commented Sep 16, 2013 at 9:36
  • 3
    Well, I'd say in line 4 you read every line one by one and change it in the following lines. If you do not want to do that, then dont! Commented Sep 16, 2013 at 9:40

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.