2013年8月27日

on
一、啟用JSON: http://php.net/manual/en/book.json.php
1 
二、JSON 建立與解析: 
(1)建立json:
 
$json_data = array ('id'=>1,'name'=>"mike",'country'=>'usa',"office"=>array("microsoft","oracle"));
echo json_encode($json_data); 

(2)解析json:
$json_string='{"id":1,"name":"mike","country":"usa","office":["microsoft","oracle"]} ';
$obj=json_decode($json_string);
echo $obj->name; //displays mike
 
echo $obj->office[0]; //displays microsoft
[資料來源參考:Creating and Parsing JSON data with PHP]

三、基本解析Firefox - demo.json書籤備份檔:
$myfile = file_get_contents("demo.json","r");
$filecontent=preg_replace('/,\s*([\]}])/m', '$1',$myfile);
$myJson=json_decode($filecontent);
if (count($myJson->children) > 0)
{
   for($i=0;$i<count($myJson->children);$i++)
   {
    echo $myJson->children[$i]->title; //取得根目錄名稱
 
    echo "<br />\n";
   }
}
或 
$myfile = file_get_contents("demo.json","r");
$filecontent=preg_replace('/,\s*([\]}])/m', '$1',$myfile);
$myJson=json_decode($filecontent);
foreach($myJson->children as $itemA)
{
    echo $itemA->title; //取得根目錄名稱
    foreach($itemA->children as $itemB)
    {
      echo $itemB->title; //取得子目錄名稱
    }
}
2 
四、延伸閱讀:
(1)JSON stylesheets - JSSS : 
http://www.maraksquires.com/json_stylesheets/

(2)JSONLint - The JSON Validator. : 
http://www.jsonlint.com/

(3)Collapsible JSON Formatter - view your json code in colors : 
http://www.bodurov.com/JsonFormatter/

(4)Mr. Data Converter : 輸入CSV格式資料,轉換成JSON. XML, Python,等格式. 
http://www.shancarter.com/data_converter/index.html

0 意見:

張貼留言

注意:只有此網誌的成員可以留言。