Skip to content

Instantly share code, notes, and snippets.

@mubbashar
Last active August 17, 2016 12:49
Show Gist options
  • Select an option

  • Save mubbashar/e96561afbbf258591ad09b0bfcac76bf to your computer and use it in GitHub Desktop.

Select an option

Save mubbashar/e96561afbbf258591ad09b0bfcac76bf to your computer and use it in GitHub Desktop.
PHP JSON TO CSV Listener using salsify/jsonstreamingparser
<?php
namespace App\Test\JSONListener;
use \JsonStreamingParser\Listener;
class JSON2CSV implements Listener
{
private $_current_row;
private $_outfile;
private $_key;
private $_header_written;
public function __construct($outputFileName)
{
$this->_outfile = fopen($outputFileName, 'w');
}
public function startDocument()
{
$this->_current_row = array();
$this->_key = null;
$this->_header_written = false;
}
public function endDocument()
{
fclose($this->_outfile);
}
public function startObject()
{
$this->_current_row = array();
}
public function endObject()
{
if (!$this->_header_written) {
fputcsv($this->_outfile, array_keys($this->_current_row));
$this->_header_written = true;
}
fputcsv($this->_outfile, $this->_current_row);
}
public function startArray()
{
$this->startObject();
}
public function endArray()
{
$this->endObject();
}
// Key will always be a string
public function key($key)
{
$this->_key = $key;
}
// Note that value may be a string, integer, boolean, null
public function value($value)
{
if ($this->_key) {
$this->_current_row[$this->_key] = $value;
$this->_key = null;
}
}
public function whitespace($whitespace)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment