Posted By

ecavazos on 01/21/08


Tagged

php json sting


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

JimiJay
jamarama
mikegreen
hamiltonmascioli
vali29
Juntalis
nb109
voove
tux-world


Output JSON String from PHP


 / Published in: PHP
 

URL: http://snipplr.com/view/4715/simple-data-access-class/

This snippet references the data access class I linked to.

  1. // query parameters
  2. $p[0] = 'id';
  3. $p[1] = 'name';
  4.  
  5. // query database
  6. $result = $dal->selectFieldsOrder('inventory_categories', $p, 'name asc');
  7.  
  8. $numRows = $result->num_rows;
  9. $loopCount = 1;
  10.  
  11. $json = '{ '
  12. . '"categories" : [';
  13.  
  14. // build json string
  15. while ($row = $result->fetch_assoc()) {
  16. $json .= '{ '
  17. . '"id" : "' . $row['id'] . '", '
  18. . '"name" : "' . addcslashes($row['name'], '"') . '" '
  19. . '}';
  20.  
  21. // add comma if
  22. if ($loopCount < $numRows) {
  23. $json .= ', ';
  24. $loopCount++;
  25. }
  26. }
  27.  
  28. $json .= '] '
  29. . '}';
  30.  
  31. echo $json;

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: andyman3000 on January 27, 2008

or just use json_encode() (from php 5.2.0): http://php.net/manual/en/function.json-encode.php

You need to login to post a comment.