2010年3月26日 星期五

[PHP]PHP 結合 ADODB 產生 json 教學

今天在需要運用 PHP 結合 ADODB 產生 json,於是找到了這篇「Handy AJAX data structures using JSON, XML, ADODB, PHP, and Mysql」教學,將 tojson.inc.php 檔放入 adodb/ 目錄下,即可運用了 ^^

tojson.inc.php
CODE:

/**
* Creates JSON ( http://www.json.org/ ) from the ADODB record set
*
* @param object $rs - record set object
* @param bool $moveFirst - determines whether recordset is returned to first record
* @return string $output - resulting json string
* @version V1.0 10 June 2006 (c) 2006 Rich Zygler ( http://www.boringguys.com/ ). All rights reserved.
*
* Released under both BSD license and Lesser GPL library license. You can choose which license
* you prefer.

Example output from query "SELECT Name, Continent From Country LIMIT 10;"

{"rows":[
{"row":{"Name":"Afghanistan","Continent":"Asia"}},
{"row":{"Name":"Netherlands","Continent":"Europe"}},
{"row":{"Name":"Netherlands Antilles","Continent":"North America"}},
{"row":{"Name":"Albania","Continent":"Europe"}},
{"row":{"Name":"Algeria","Continent":"Africa"}},
{"row":{"Name":"American Samoa","Continent":"Oceania"}},
{"row":{"Name":"Andorra","Continent":"Europe"}},
{"row":{"Name":"Angola","Continent":"Africa"}},
{"row":{"Name":"Anguilla","Continent":"North America"}},
{"row":{"Name":"Antigua and Barbuda","Continent":"North America"}}
]}

*/

function rs2json($rs, $moveFirst = false)
{
if (!$rs)
{
printf(ADODB_BAD_RS,'rs2json');
return false;
}

$output = '';
$rowOutput = '';

$output .= '{"rows":';
$totalRows = $rs->numrows();

if($totalRows > 0)
{
$output .= '[';
$rowCounter = 1;
while ($row = $rs->fetchRow())
{
$rowOutput .= '{"row":{';
$cols = count($row);
$colCounter = 1;

foreach ($row as $key => $val)
{
$rowOutput .= '"' . $key . '":';
$rowOutput .= '"' . $val . '"';

if ($colCounter != $cols)
{
$rowOutput .= ',';
}
$colCounter++;
}

$rowOutput .= '}}';

if ($rowCounter != $totalRows)
{
$rowOutput .= ',';
}
$rowCounter++;
}
$output .= $rowOutput . ']';
}
else
{
$output .= '"row"';
}

$output .= '}';

if ($moveFirst)
{
$rs->MoveFirst();
}
return $output;
}



Example

<?php

require_once('Adodb/adodb.inc.php');
require_once('Adodb/tojson.inc.php');

// we're using the mysql "world" database downloadable from http://dev.mysql.com/doc/
$dbType = 'mysql';
$dbHost = 'localhost';
$dbName = 'world';
$dbUser = 'test';
$dbPass = 'test';

$db = ADONewConnection($dbType);
$db->Connect($dbHost, $dbUser, $dbPass, $dbName);
$db->SetFetchMode(ADODB_FETCH_ASSOC);

$sql = "SELECT * FROM Country LIMIT 10";
$result = $db->Execute($sql);

if(!$result)
{
echo $db->ErrorMsg();
}
else
{
echo rs2json($result);

// you may want to utf8_encode the results instead (works better in IE this way)
//echo utf8_encode(rs2json($result));
}

$result->close();
$db->close();

?>


英文網址:http://blog.boringguys.com/2006/08/handy-ajax-data-structures-using-json.html

沒有留言: