2013-10-02 102 views
0

我正在嘗試在我的網站上顯示jsonJSON應該正確格式化,但它被包裝。顯示右格式化json

目前,它是:

{ 「IDS」:[{ 「ID」: 「52」, 「名」: 「\ u0633 \ u0633 \ u064a約翰」, 「性」:」 \ u0635 \ u0628 \ u064a 「 」國籍「: 」德國「},{ 」ID「: 」50「, 」名「: 」\ u0645 \ u062d \ u0645 \ u062f sjajha 醫管局「, 」性「:」 \ u0630 \ u0643 \ u0631" , 「國籍」: 「\ u0628 \ u062d \ u0631 \ u0627 \ u0646 \ u064a」}], 「成功」:1}

而它應該是這樣的:

{ 
    "success": 1, 
    "product": [ 
     { 
      "pid": "1", 
      "name": "iPHone 4S", 
      "price": "300.00", 
      "description": "iPhone 4S white", 
      "created_at": "2012-04-29 01:41:42", 
      "updated_at": "0000-00-00 00:00:00" 
     } 
    ] 
} 

這是我的PHP代碼:

<html> 
<head> 
<title>Send and Rec data to Android Device</title> 
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/> 

</head> 


<body> 

<?php 

/* 
* Following code will list all the ids 
*/ 
$db = mysql_connect($dbhost, $dbuser, $dbpass); 

    mysql_query("SET character_set_results = 'utf8', character_set_client = 'utf8', character_set_connection = 'utf8', character_set_database = 'utf8', character_set_server = 'utf8'", $db); 
    mysql_set_charset('utf8', $db); 

    $charset = mysql_client_encoding($db); 

// array for JSON response 
$response = array(); 

// include db connect class 
// connecting to db 

// get all ids from ids table 
$result = mysql_query("SELECT * FROM people") or die(mysql_error()); 

// check for empty result 
if (mysql_num_rows($result) > 0) { 
    // looping through all results 
    // ids node 
    $response["ids"] = array(); 

    while ($row = mysql_fetch_array($result)) { 
     // temp user array 
     $idd = array(); 
     $idd["id"] = $row["id"]; 
     $idd["name"] = $row["name"]; 
     $idd["sex"] = $row["sex"]; 
     $idd["nationality"] = $row["nationality"]; 

     // push single idd into final response array 
     array_push($response["ids"], $idd); 
    } 
    // success 
    $response["success"] = 1; 

    // echoing JSON response 
    echo json_encode($response); 
} else { 
    // no ids found 
    $response["success"] = 0; 
    $response["message"] = "No ids found"; 

    // echo no users JSON 
    echo json_encode($response); 
} 
?> 

</body> 


</html> 
+0

而不是'array_push($ response [「ids」],$ idd);'use' $ response ['product'] [] = $ idd;'(或者類似的,你的json和php代碼是不一樣的...) – Rufinus

+0

沒有什麼改變,仍然是相同的包裝。 –

+0

爲什麼它被標記爲android問題?你需要在android中嗎?如果你這樣做是jObject.ToString(number_of_space); –

回答

0

在PHP 5.4.0+你JSON_PRETTY_PRINT選項與壓印打印JSON(易於讀取的格式)。

echo json_encode($json, JSON_PRETTY_PRINT); 

編號:http://www.php.net/manual/en/function.json-encode.php#refsect1-function.json-encode-changelog

但是你要打印出來的文本區域或預標記。像這樣

echo '<pre>'.json_encode($json, JSON_PRETTY_PRINT).'</pre>'; 
//or 
echo '<textarea cols="50" rows="20">'.json_encode($json, JSON_PRETTY_PRINT).'</textarea>'; 
+0

我用這個,但我得到**警告:json_encode()期望的是1個參數,2 xxxx.php給出線61 ** –

+0

您需要的PHP版本5.4.0以上使用此代碼。 – Chokchai

+0

嘿。我發現這個請看看http://www.daveperrett.com/articles/2008/03/11/format-json-with-php/ – Chokchai