Mike Mike - 28 days ago 5x
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?


[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]



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 ...