Mike Mike - 2 months ago 9
PHP Question

How do I parse a CSV where each row is enclosed in square brackets using PHP?

I've stumbled across a CSV-ish format whilst trying pass a feed received from Transport for London. What would be the best method to parse this using PHP?

http://countdown.api.tfl.gov.uk/interfaces/ura/instant_V1?circle=51.49288,-0.147425,100&ReturnList=StopPointName,EstimatedTime,StopID

[4,"1.0",1418639278611]
[1,"Eccleston Bridge","35312",1418639472000]
[1,"Eccleston Bridge","35312",1418639395000]
[1,"Eccleston Bridge","35312",1418639397000]
[1,"Eccleston Bridge","35312",1418639696000]
[1,"Eccleston Bridge","35312",1418639742000]
[1,"Eccleston Bridge","35312",1418639731000]
[1,"Eccleston Bridge","35312",1418640051000]
[1,"Eccleston Bridge","35312",1418639938000]
...


Thanks.

Answer

As each row individually looks like JSON, you could use json_decode() here:

// input as string
$input = '....';

// split by lines
$lines = explode( "\n", $input );

// walk through results
for( $i=0; $i<count($lines); $i++ ) {

  // parse row
  $row = json_decode( $lines[i] );

  // do something with it ...

}
Comments