-2

I need to to replace comma "," by "->" as multiple value separator on category field of csv, on a php script. In the attached example csv piece, the field value on first row is

;ALIMENTACIÓN,GRANEL,Cereales legumbres y frutos secos,Desayuno y entre horas,Varios;

I neet to be replaced to:

;ALIMENTACIÓN->GRANEL->Cereales legumbres y frutos secos->Desayuno y entre horas->Varios;

I tried this code on my php script:

file_put_contents("result.csv",str_replace(",","->",file_get_contents("origin.csv")));

And it works, but it replace comma on all fields. but i need to change only on this Catefory field. It is, i need do no replace commas on description field, or other fields.

Thank you, in advance

Piece of my csv file as example (header and 3 rows -i truncated description field-):

id;SKU;DEFINICION;AMPLIACION;DISPONIBLE;IVA;REC_EQ;PVD;PVD_IVA;PVD_IVA_REC;PVP;PESO;EAN;HAY_FOTO;IMAGEN;FECHA_IMAGEN;CAT;MARCA;FRIO;CONGELADO;BIO;APTO_DIABETICO;GLUTEN;HUEVO;LACTOSA;APTO_VEGANO;UNIDAD_MEDIDA;CANTIDAD_MEDIDA;
1003;"01003";"COPOS DE AVENA 1000GR";"Los copos son granos de cereales que han sido aplastados para facilitar su digestion, manteniendo integras las propiedades del grano.<br>
La avena contiene proteínas en abundancia, así como hidratos de carbono, grasas saludables...";59;2;1.40;2.20;2.42;2.45;3.14;1;"8423266500305";1;"https://distribudiet.net/webstore/images/01003.jpg";"04/03/2020 0:00:00";ALIMENTACIÓN,GRANEL,Cereales legumbres y frutos secos,Desayuno y entre horas,Varios;GRANOVITA;0;0;0;0;1;0;0;1;kilo;1
1018;"01018";"MUESLI 10 FRUTAS 1000GR";"Receta de muesli de cereales, diez tipos diferentes de deliciosas frutas desecadas, frutos secos, semillas de girasol, lino y sesamo.<br>
A finales del ...";63;2;1.40;4.66;5.13;5.19;6.65;1;"8423266500060";1;"https://distribudiet.net/webstore/images/01018.jpg";"04/03/2020 0:00:00";ALIMENTACIÓN,GRANEL,Desayuno y entre horas;GRANOVITA;0;0;0;0;;0;0;1;kilo;1
1037;"01037";"AZUCAR CAÑA INTEGRAL 1000GR";"Azúcar moreno de caña integral sin gluten para endulzar todo tipo de postres, batidos o tus recetas favoritas de repostería. 100% natural, obtenido sin procesamiento quimico por ...";17;2;1.40;3.43;3.77;3.82;4.90;1;"8423266500121";1;"https://distribudiet.net/webstore/images/01037.jpg";"04/03/2020 0:00:00";ALIMENTACIÓN,GRANEL,Endulzantes;GRANOVITA;0;0;0;0;0;0;0;1;kilo;1
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
iostream
  • 11
  • 1

1 Answers1

0
<?php

$input = 'PRESTA.csv';
$output = 'OUTPUT.csv';

$file = str_replace("<br>\n", "<br>", file_get_contents($input)); // Remove newlines in description
$lines = explode("\r\n", $file); // Split the file into lines

$fp = fopen($output, 'w'); // Open output file for writing

for ($i = 0; $i < count($lines); ++$i) {
    $extract = str_getcsv($lines[$i], ';'); // Split using ; delimeter
    if ($i > 0 && isset($extract[16])) // Only replace on the 16th field "CAT"
        $extract[16] = str_replace(',', '->', $extract[16]);
    else
        var_dump($extract); // There are some lines that dont have a CAT field

    fputcsv($fp, $extract, ';'); // Write line to file using ; delimeter
}

fclose($fp);
Jacob Mulquin
  • 3,458
  • 1
  • 19
  • 22
  • Thank you, very much for you help. I tried to use this code. Sorry because i'm not much experienced on it, but when i run i see this message: Warning: array_combine(): Both parameters should have an equal number of elements in /var/www/vhosts/.../script.php on line 14 And i see that on result.csv i got on all file: Array Array Array Array Array – iostream Sep 26 '21 at 13:25
  • I opened on excel to see if different number of elementes on header than rest, but seems all right, 28 columns as header and as values. On sample code i putted a piece of csv with header and 3 rows but i got same issue about Array,,, Thank you! – iostream Sep 26 '21 at 13:49
  • I had to edit the CSV you provided in the sample, the first product was on the same line as the headers. Make sure that none of the rows have a `;` at the end of them – Jacob Mulquin Sep 26 '21 at 20:02
  • I see that first header row has ; on final, and i dleted, but i have same issue, and seems all right, and i open on Excel and open well, header on first row and others on its rows... I'm getting same issue... This is the file i use: https://www.herbishop.com/webservice/origins/test.csv Thank you! – iostream Sep 27 '21 at 16:34
  • @iostream The problem with that file is the newline after `
    `, the `file` function in php splits a file per line. Excel has some smarts in it and it knows to ignore new lines inside a quoted field.
    – Jacob Mulquin Sep 27 '21 at 20:15
  • Oh, thank you... but how can i get the result i want on this csv file? The complete csv is this: herbishop.com/webservice/origins/PRESTA_C_lB6W_2_art_total.csv – iostream Sep 27 '21 at 22:44
  • @iostream I have updated the answer, there appears to be some lines that don't have all the fields in the input csv. You will need to clean them manually first. – Jacob Mulquin Sep 27 '21 at 23:16