json_encode()
是 PHP 中用于將數組或對象轉換為 JSON 格式的字符串的函數。以下是如何使用 json_encode()
實現數據格式轉換的示例:
<?php
$assoc_array = array(
"name" => "John",
"age" => 30,
"city" => "New York"
);
$json_string = json_encode($assoc_array);
echo $json_string;
?>
輸出:
{"name":"John","age":30,"city":"New York"}
<?php
$multi_dim_array = array(
array(
"name" => "John",
"age" => 30,
"city" => "New York"
),
array(
"name" => "Jane",
"age" => 28,
"city" => "San Francisco"
)
);
$json_string = json_encode($multi_dim_array);
echo $json_string;
?>
輸出:
[
{"name":"John","age":30,"city":"New York"},
{"name":"Jane","age":28,"city":"San Francisco"}
]
<?php
class Person {
public $name;
public $age;
public $city;
public function __construct($name, $age, $city) {
$this->name = $name;
$this->age = $age;
$this->city = $city;
}
}
$person = new Person("John", 30, "New York");
$json_string = json_encode($person);
echo $json_string;
?>
輸出:
{"name":"John","age":30,"city":"New York"}
注意:json_encode()
函數在處理特殊字符(如非 ASCII 字符)時可能會返回 null
或拋出警告。為了避免這些問題,可以使用 JSON_UNESCAPED_UNICODE
選項來保留 Unicode 字符:
<?php
$json_string = json_encode($assoc_array, JSON_UNESCAPED_UNICODE);
echo $json_string;
?>
輸出:
{"name":"John","age":30,"city":"紐約"}