ab24 ab24 - 6 months ago 11
PHP Question

convert mysqli result to json

I have a mysqli query which i need to format as json for a mobile application.

I have managed to produce an xml document for the query results, however i am looking for something more lightweight. (see below for my current xml code)

Any help or info greatly appreciated people!

$mysql = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME) or die('There was a problem connecting to the database');

$stmt = $mysql->prepare('SELECT DISTINCT title FROM sections ORDER BY title ASC');

// create xml format
$doc = new DomDocument('1.0');

// create root node
$root = $doc->createElement('xml');
$root = $doc->appendChild($root);

// add node for each row
while($row = $stmt->fetch()) :

$occ = $doc->createElement('data');
$occ = $root->appendChild($occ);

$child = $doc->createElement('section');
$child = $occ->appendChild($child);
$value = $doc->createTextNode($title);
$value = $child->appendChild($value);


$xml_string = $doc->saveXML();

header('Content-Type: application/xml; charset=ISO-8859-1');

// output xml jQuery ready

echo $xml_string;

$mysqli = new mysqli('localhost','user','password','myDatabaseName');
$myArray = array();
if ($result = $mysqli->query("SELECT * FROM phase1")) {

    while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = $row;
    echo json_encode($myArray);

  1. $row = $result->fetch_array(MYSQL_ASSOC)
  2. $myArray[] = $row

output like this: