> For the complete documentation index, see [llms.txt](https://phper.shujuwajue.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://phper.shujuwajue.com/phpwen-jian-bian-cheng/phpzhong-json-chu-li.md).

# PHP中JSON处理

## json\_encode

* json\_encode 目前只能处理UTF-8编码的数据
* JSON\_UNESCAPED\_UNICODE 让JSON更懂中文
* 解析出错，看[ json\_last\_error() ](http://php.net/manual/zh/function.json-last-error.php)返回的错误
* JSON格式是灵活开放的，特殊情况可以用sprintf来自己组装或者解析JSON字符串

语法:

```php
string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
```

参数:

* JSON\_HEX\_TAG   所有的 < 和 > 转换成 \u003C 和 \u003E&#x20;
* JSON\_HEX\_AMP   所有的 & 转换成 \u0026
* JSON\_HEX\_APOS  所有的 ' 转换成 \u0027
* JSON\_HEX\_QUOT 所有的 " 转换成 \u0022
* JSON\_FORCE\_OBJECT  强制使用索引数组输出
* JSON\_NUMERIC\_CHECK 将所有数字字符串编码成数字
* JSON\_BIGINT\_AS\_STRING  将大数字编码成原始字符原来的值
* JSON\_PRETTY\_PRINT  用空白字符格式化返回的数据
* JSON\_UNESCAPED\_SLASHES  不要编码 /
* JSON\_UNESCAPED\_UNICODE 以字面编码多字节 Unicode 字符（默认是编码成 \uXXXX）

示例

**JSON\_PRETTY\_PRINT** ,有的时候需要查看,所以中格式化的效果更美观

```php
$arr = array('a' => 'b' , 'b' => 'c');
echo json_encode($arr, JSON_PRETTY_PRINT);
echo "\n";
echo json_encode($arr);
```

结果:

```php
{
    "a": "b",
    "b": "c"
}
{"a":"b","b":"c"}
```

[json\_encode($b, JSON\_FORCE\_OBJECT) 可以强制转换成对象](http://blog.163.com/spring_51888/blog/static/43279623201532110314750/)

## json\_decode

```php
 json_decode($res, true);
```

## 拼装json

简单示例:

```php
$format = '["%s",%d,%b]';
$jsonstr= sprintf($format, '张三', 15 , false );
echo $jsonstr;
echo "\n";
$json=json_decode($jsonstr);
echo "\n";
print_r($json);
echo json_last_error_msg();
```

结果:

```
["张三丰",16,0]

Array
(
    [0] => 张三丰
    [1] => 16
    [2] => 0
)
No errorr
```

封装函数:

```php
$arr = ['北京'=>['a',123=>[] ],'热门'];
$arr = array('a' => 'b');
echo encode($arr);

 function encode($data) {
    switch ($type = gettype($data)) {
        case 'NULL':
            return 'null';
        case 'boolean':
            return ($data ? 'true' : 'false');
        case 'integer':
        case 'double':
        case 'float':
            return $data;
        case 'string':
            return '"' . addcslashes($data, "\r\n\t\"") . '"';
        case 'object':
            $data = get_object_vars($data);
        case 'array':
            $count = 0;
            $indexed = array();
            $associative = array();
            foreach ($data as $key => $value) {
                if($count !== NULL && (gettype($key) !== 'integer' || $count++ !== $key)) {
                    $count = NULL;
                }
                $one = encode($value);
                $indexed[] = $one;
                $associative[] = encode($key) . ':' . $one;
            }
            if ($count !== NULL) {
                return '[' . implode(',', $indexed) . ']';
            } else {
                return '{' . implode(',', $associative) . '}';
            }
        default:
        return ''; // Not supported
    }
}
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://phper.shujuwajue.com/phpwen-jian-bian-cheng/phpzhong-json-chu-li.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
