JSON PHP

❮ 前章へ 次章へ ❯

JSONの一般的な使い方は、Webサーバからデータを読み、そのデータをWebページに表示することです。

この章では、クライアントとPHPサーバの間でJSONデータを交換する方法を説明します。


PHP ファイル

PHPには、JSONを処理する組み込み関数がいくつかあります。

PHPのオブジェクトをJSONに変換するには、PHP関数のjson_encode()を使用します:

PHP ファイル

<?php
$myObj->name = "John";
$myObj->age = 30;
$myObj->city = "New York";

$myJSON = json_encode($myObj);

echo $myJSON;
?>
Show PHP file »

クライアントJavaScript

上の例の PHP ファイルをリクエストする、AJAX呼び出しを使用したクライアントのJavaScriptを次に示します:

結果を、JavaScriptオブジェクトに変換するためにJSON.parse()を使用します:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj.name;
    }
};
xmlhttp.open("GET", "demo_file.php", true);
xmlhttp.send();
Try it Yourself »

PHP配列

PHP関数json_encode()を使用すれば、PHPの配列もJSONに変換できます:

PHP ファイル

<?php
$myArr = array("John", "Mary", "Peter", "Sally");

$myJSON = json_encode($myArr);

echo $myJSON;
?>
Show PHP file »

クライアントJavaScript

上の配列の例のPHPファイルをリクエストする、AJAX呼び出しを使用したクライアント上のJavaScriptを次に示します:

結果を、JavaScript配列に変換するためにJSON.parse()を使用します:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        document.getElementById("demo").innerHTML = myObj[2];
    }
};
xmlhttp.open("GET", "demo_file_array.php", true);
xmlhttp.send();
Try it Yourself »

PHPデータベース

PHPはサーバ側のプログラミング言語であり、データベースへのアクセスのような、サーバでのみ実行可能な操作に使用する必要があります。

customers、products、suppliers を含む、データベースがサーバにあったとします。

"customers" テーブルの最初の10レコードをリクエストする、サーバへのリクエストを作ろうと思います:

JSON.stringify()を使用して、JavaScriptオブジェクトをJSONに変換します:

obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
};
xmlhttp.open("GET", "json_demo_db.php?x=" + dbParam, true);
xmlhttp.send();
Try it Yourself »

例の説明:

PHPファイルを見てみましょう:

PHP file

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false);

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>

PHPファイルの説明:

結果をループする

PHPファイルから受信した結果を、JavaScriptオブジェクト(この場合はJavaScript配列)に変換します:

JSON.parse()を使用してJSONをJavaScriptオブジェクトに変換します:

...
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x].name + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
...
Try it Yourself »

PHP メソッド = POST

サーバにデータを送信する場合は、HTTP POSTメソッドを使用するのが最善の方法です。

POSTメソッドを使用してAJAXリクエストを送信するには、メソッドと正しいヘッダを指定します。

サーバに送信されたデータは、.send()メソッドの引数でなければなりません:

obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        myObj = JSON.parse(this.responseText);
        for (x in myObj) {
            txt += myObj[x] + "<br>";
        }
        document.getElementById("demo").innerHTML = txt;
    }
};
xmlhttp.open("POST", "json_demo_db_post.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
Try it Yourself »

PHPファイルでの唯一の違いは、転送データの取得方法です。

PHPファイル

$ _GETの代わりに$ _POSTを使用してください:

<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);

$conn = new mysqli("myServer", "myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);

echo json_encode($outp);
?>

❮ 前章へ 次章へ ❯