Skip to content

Instantly share code, notes, and snippets.

@sul4bh
Last active April 1, 2021 07:08
Show Gist options
  • Save sul4bh/d392315c7049abd86916e077707bf123 to your computer and use it in GitHub Desktop.
Save sul4bh/d392315c7049abd86916e077707bf123 to your computer and use it in GitHub Desktop.
Parse a multiline csv string in php
<?php
$csvString = "ID,Condition,Condition,Condition,Condition,AdSize,Content:Text,Content:Text,Content:Text,Content:ImageUrl,Content:LandingPageUrl,Archive,Default
ID,Locations:Region,Device Properties:Device,Weather:Condition,Dmp:Liveramp,AdSize,title1,description1,price1,imageUrl1,landingPageUrl1,Archive,Default
ROW_001,\"Wa, Ca, Tn\",Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/Snow.jpg,https://www.example.com,TRUE,
ROW_002,Wa,Mobile,Snow,12345,300x250,Hello Washingtonian,My Custom Description,10,http://domain/New_Snow.jpg,https://www.example.com,,
ROW_003,Wa,Mobile,,,300x250,Hello Washingtonian,My Custom Description,10,http://domain/clear.jpg,https://www.example.com,,
ROW_004,,,,,300x250,Hello,My Custom Description,20,http://domain/clear.jpg,https://www.example.com,,TRUE";
function csvToArray($csvString, $delimiter = ',', $lineBreak = "\n") {
$csvArray = [];
$rows = str_getcsv($csvString, $lineBreak); // Parses the rows. Treats the rows as a CSV with \n as a delimiter
foreach ($rows as $row) {
$csvArray[] = str_getcsv($row, $delimiter); // Parses individual rows. Now treats a row as a regular CSV with ',' as a delimiter
}
return $csvArray;
}
print_r(csvToArray($csvString));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment