I normally use the PHP PDO to retrieve data from a MySQL database, and then convert the data to JSON after calling $statement->fetchAll(PDO::FETCH_ASSOC).  This has worked well for me, and each row is converted into its own row in the JSON based on column name and value.

So, when I recently tried it with the OCI adapter ( oci_fetch_all($statement,OCI_ASSOC) ), the results turned out different than I expected.  Rather than returning a result set of column names to values for each row, I ended up with an array of column names, each with their own array of values:

[COLUMN_ONE]=>array(‘value1′,’value2′,’value3’,etc.), [COLUMN_TWO]=>array(‘value1′,’value2′,’value3’,etc.)

while what I really needed was the following

[COLUMN_ONE]=>’value1′,[COLUMN_TWO]=>’value1′
[COLUMN_ONE]=>’value2′,[COLUMN_TWO]=>’value2′
[COLUMN_ONE]=>’value3′,[COLUMN_TWO]=>’value3′

The fix turned out to be fairly straightforward.  I simply needed to force each row into another array so that the items would encode properly:

$json = array();
while($data = oci_fetch_array($stid,OCI_ASSOC))
{
          $json[] = $data;
}

That did the trick.

2 thoughts on “Converting Oracle (OCI) Results to JSON with PHP

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.