如何在PHP中创建json文件

时间:2013-02-25 05:50:05

标签: php json

我需要从头开始创建一个看起来像这样的JSON文件

{
 "results": {
  "course": "CC167",
  "books": {
   "book": [
    {
      "-id": "585457",
      "-title": "Beginning XNA 20 game programming : from novice to professional",
      "-isbn": "1590599241",
      "-borrowedcount": "16"
    },
    {
      "-id": "325421",
      "-title": "Red Hat Linux 6",
      "-isbn": "0201354373",
      "-borrowedcount": "17"
    },
    {
      "-id": "424317",
      "-title": "Beginner's guide to darkBASIC game programming",
      "-isbn": "1592000096",
      "-borrowedcount": "46"
    },
    {
      "-id": "437390",
      "-title": "Objects first with Java : a practical introduction using BlueJ",
      "-isbn": "0131249339",
      "-borrowedcount": "89"
    },
    {
      "-id": "511094",
      "-title": "Objects first with Java : a practical introduction using BlueJ",
      "-isbn": "2006044765",
      "-borrowedcount": "169"
    }
   ]
  }
 }
}

这是我以前用过的PHP,所以希望它不是一个很大的跳跃,但我不知道如何从头开始在PHP中创建JSON对象,只有如何制作这样的东西然后保存它本身就是一个JSON

$y = 1;
    $json = "{";
    $json = $json . "\"results\": {";
    $json = $json . "\"course\": \"$cc\",";
    $json = $json . "\"books\": {";
    $json = $json . "\"book\": [";
    foreach ($my_array as $counter => $bc) {
        $json = $json . "{";
        $json = $json . "\"-id\": \"$id[$counter]\",";
        $json = $json . "\"-title\": \"$title[$counter]\",";
        $json = $json . "\"-isbn\": \"$isbn[$counter]\",";
        $json = $json . "\"-borrowedcount\": \"$borrowedcount[$counter]\"";
        $json = $json . "}";
        if ($x != $y) $json = $json .  ",";
        $json = $json . "";
        $y++;
    }
    $json = $json . "]";
    $json = $json . "}";
    $json = $json . "}";
    $json = $json . "}";
    echo $json;

2 个答案:

答案 0 :(得分:4)

您可以使用json_encode

从PHP中的数组生成json

例如,这将生成类似于上面的json(略微缩减)

的内容
$data = array(
  "results" => array(
    "course" => "CC167",
    "books" => array(
      "book" =>
      array(
        array(
          "-id" => "585457",
          "-title" => "Beginning XNA 20 game programming : from novice to professional",
          "-isbn" => "1590599241",
          "-borrowedcount" => "16"
        ),
        array(
          "-id" => "325421",
          "-title" => "Red Hat Linux 6",
          "-isbn" => "0201354373",
          "-borrowedcount" => "17"
        )
      )
    )
  )
);
echo json_encode($data);

尝试通过手动字符串连接生成json(如在当前代码中)是不好的主意,因为它难以避免语法错误,您需要转义json的动态部分。 json_encode会自动为你逃脱。

答案 1 :(得分:0)

试试这个:

$array       = array("test"=>"value");

$json_string = json_encode($array);

参考:http://php.net/manual/en/function.json-encode.php