Home > Net >  I don't manage to parse properly a CSV file with "|" delimeter using PHP
I don't manage to parse properly a CSV file with "|" delimeter using PHP

Time:03-19

I'm trying to parse a CSV file.

<?php
$url = 'https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';
$csv = array_map('str_getcsv', file($url), ["|"]);
echo '<pre>'; echo print_r ($csv); echo '</pre>';
?>

Here is a sample of what i get :

[1] => Array
    (
        [0] => 5016488133494|Ary And The Secret Of Seasons PS4|100001|9.99||Jeu > PS4|https://xht.micromania.fr/?P3CB0566CA125FS1UD41282b0253295V4|https://edge.disstg.commercecloud.salesforce.com/dw/image/v2/BCRB_STG/on/demandware.static/-/Sites-masterCatalog_Micromania/default/dw65159733/images/high-res/100001.jpg?sw=1000|JUST FOR GAMES|JUST FOR GAMES|Explorez le monde merveilleux de Valdi !||new|4.99|||||||2
    )

Apparently, the parser doesn't take every "|" into account.

CodePudding user response:

If you inspect your output, you'll notice that the split works on your first row. This is because (oddly) PHP only uses the extra args once per iteration, so you'd need to specify them for each row:

array_map('str_getcsv', file($url), ["|", "|", "|", ...]);

... which makes not a whole lot of sense to me, as you don't know how many rows you have. I'd just call it explicitly like this instead:

$csv = array_map(fn($line) => str_getcsv($line, '|'), file($file));

Or the older style:

$csv = array_map(function($line) { return str_getcsv($line, '|'); }, file($file));

CodePudding user response:

Here's a script I suggest. It assembles csvArray as result, I hope you'll handle further:

<?php
$url='https://flux.netaffiliation.com/feed.php?maff=3E9867FCP3CB0566CA125F7935102835L51118FV4';

$file_name = 'csvToParse.csv';

$arrContextOptions=array(
   "ssl"=>array(
        "verify_peer"=>false,
        "verify_peer_name"=>false,
    ),
); 

file_put_contents($file_name, file_get_contents($url, false, 
stream_context_create($arrContextOptions)));

$fopenCSVHandle=fopen($file_name, 'r');
$csvArray=array();

if ($fopenCSVHandle !== false){
     while (($data = fgetcsv($fopenCSVHandle, 1000, "|")) !== FALSE) {
    //echo('<br />single row $data=<br />');
    //print_r($data);
    $csvArray[]=$data;
 }
    
//echo('<br />We got this $data from CSV:<br />');
//print_r($csvArray);
}

?>
  • Related