0

This must be relatively easy, but I'm struggling to find a solution. I receive data using proprietary network protocol with encryption and at the end the entire received content ends up in a variable. The content is actually that of a CSV file - and I need to parse this data.

If this were a regular file on disk, I could use fgetcsv; if I could somehow break the content into individual records, I could use str_getcsv - but how can I break this file into records? Simple reading until a newline will not work, because CSV can contain values with line breaks in them. Below is an example set of data:

ID,SLN,Name,Address,Contract no
123,102,Market 1a,"Main street, Watertown, MA, 02471",16
125,97,Sinthetics,"Another address,
Line 2
City, NY 10001",16
167,105,"Progress, ahead",,18

All of this data is held inside one variable - and I need to parse it.

Of course, I can always write this data into a temporary file on disk the read/parse it using fgetcsv, but it seems extremely inefficient to me.

Aleks G
  • 56,435
  • 29
  • 168
  • 265
  • [Here](http://stackoverflow.com/questions/11337221/codeigniter-rest-csv-import-to-mysql/11339125#11339125) is the answer. Use this library – Muhammad Raheel Jan 21 '14 at 10:41
  • @raheelshan Did you read the question? That "library" reads from a file - and I don't have a file. If I had a file, I wouldn't be asking this question, I know how to read CSV data from a file. – Aleks G Jan 21 '14 at 10:48

1 Answers1

0

If fgetcsv works for you, consider this:

file_put_contents("php://temp",$your_data_here);
$stream = fopen("php://temp","r");
// $result = fgetcsv($stream); ...

For more on php://temp, see the php:// wrapper

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • This is perfect! Thanks! One question: if I then do `file_put_contents` in `php://temp` the second time, will it overwrite the previously written content? – Aleks G Jan 21 '14 at 10:51
  • It should do, yes. I haven't actually used `php://temp` myself, but I would imagine it would work as if you were using a file called `php_temp` instead - you can read, write, append, overwrite... – Niet the Dark Absol Jan 21 '14 at 10:58