本篇文章給大家帶來的內容是關於php如何來實現返回json資料(代碼),有一定的參考價值,有需要的朋友可以參考一下,希望對你有所協助。
一、返回格式為:
[ {"id":"1","address":"IANA"}, {"id":"2","address":"美國"}]
php代碼:
<?php header('Content-Type:application/json'); //此聲明非常重要 try { $conn = new PDO("mysql:host=localhost;dbname=orig", 'admin', 'admin'); $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->exec("SET NAMES utf8"); //設定編碼 } catch(PDOException $e) { echo "conn_error:<br/>" . $e -> getMessage(); } $sql = "select id,address from ip_segments limit 2;"; $result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); echo json_encode($result,JSON_UNESCAPED_UNICODE); //JSON_UNESCAPED_UNICODE防止中文亂碼 ?>
二、返回格式為:
{ "total":2, "rows":[ {"id":"1","address":"IANA"}, {"id":"2","address":"美國"} ]}
php代碼:
<?php header('Content-Type:application/json'); try { $conn = new PDO("mysql:host=localhost;dbname=orig", 'admin', 'admin'); $conn -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $conn->exec("SET NAMES utf8"); } catch(PDOException $e) { echo "conn_error:<br/>" . $e -> getMessage(); } $sql = "select id,address from ip_segments limit 2;"; $result = $conn->query($sql)->fetchAll(PDO::FETCH_ASSOC); $json['total'] = count($result); $json['rows'] = $result; echo json_encode($json,JSON_UNESCAPED_UNICODE); ?>
相關文章推薦:
PHP如何來建立一個軟串連(代碼)
PHP中的效能最佳化利器:php產生器的詳解