Reputation: 11
I parse CSV string and recieve wrong number of columns and i think its because of html entities like this %2C%20.
I recieve wrong number of columns and i think its because of html entities like this %2C%20.
Plese help me to parse CSV string with html entities correcrtly
$file = fopen('data://text/plain,' . $csvString, 'r+');
$fileOffers = [];
while (($data = fgetcsv($file) ) !== FALSE ) {
$fileOffers[] = $data;
}
But in one row i have this URL https://typhur.sjv.io/c/77612/1936847/18771?kw=%22valentines%20day%20gifts%2C%20valentines%20day%20gift%20for%20men%22&prodsku=AF03-DTC
Upvotes: 0
Views: 52
Reputation: 32272
The trouble is that that data://text/plain,
interpolation is interpreting the entities. @Jai's solution adds another layer of encoding to get around that, but I wouldn't expect that that will be the end of potential issues with this approach.
If you need to fake a multi-line CSV document you're better off using a temporary stream like php://temp
or php://memory
.
See: https://www.php.net/manual/en/wrappers.php.php
$file = fopen('php://temp', 'rwb');
fwrite($file, $csvString);
rewind($file);
while( ($data = fgetcsv($file)) !== FALSE ) {
$fileOffers[] = $data;
}
And if you've got just a single line of CSV that needs to be processed there's always str_getcsv()
.
Upvotes: 0
Reputation: 327
According to provided code, to parse CSV string, containing URL, using PHP, here is updated code:
$file = fopen('data://text/plain,' . urlencode($csvString), 'r+');
$fileOffers = [];
while (($data = fgetcsv($file) ) !== FALSE ) {
$fileOffers[] = $data;
}
When the URL is decoded, the value "%2C" becomes comma value, that is, "," value. To implement required functionality, in provided code, this line of code:
$file = fopen('data://text/plain,' . $csvString, 'r+');
is replaced with this line of code:
$file = fopen('data://text/plain,' . urlencode($csvString), 'r+');
It can be checked, if it works.
Upvotes: 1