Json_encode需要花费很多时间来转换为JSON作为响应

时间:2017-07-10 12:43:43

标签: php json

这是我的方案,例如我在数据库中有4000个联系人(在json_encode之后返回271257行),我已经调用了

echo json_encode($response);

但作为JSON返回响应需要35-40秒。所以我的问题是,是否还有其他选项可以将转换过程减少到json。所以我可以快速申请 我通过调用以下函数

尝试了很多
1) json_encode($response, JSON_UNESCAPED_UNICODE);

2) 
header('Content-Type: application/json')
echo json_encode($response);

3)
header('Content-Type: application/json')
echo json_encode($response); die;
  

这是单一联系人的样本数据

{
            "address": {
                "primary": {
                    "id": "",
                    "address1": "",
                    "address2": "",
                    "city": "",
                    "state": "",
                    "zipcode": "",
                    "country": "",
                    "primary-address": ""
                },
                "secondary": {
                    "id": "",
                    "address1": "",
                    "address2": "",
                    "city": "",
                    "state": "",
                    "zipcode": "",
                    "country": "",
                    "secondary-address": ""
                }
            },
            "groups": [],
            "regions": [],
            "links": [],
            "phone": [
                {
                    "type_id": 2,
                    "phone_type": "Mobile",
                    "country_code": "us",
                    "value": "+1 1830593231",
                    "is_primary": 1,
                    "country_code_value": "+1"
                }
            ],
            "social": [],
            "email": [
                {
                    "type_id": 2,
                    "type": "Work",
                    "value": "cron_4000@gmail.com",
                    "is_primary": 1
                }
            ],
            "tags": [],
            "action": {
                "is_favourite": 0,
                "is_following": 0,
                "is_stay": 0,
                "kit_expired": 0
            },
            "access": [],
            "activity_count": [],
            "contact_id": 5768,
            "type": 0,
            "salutation_id": 1,
            "assigned_to": 1,
            "first_name": "Cron 4000",
            "assigned_name": "Krunal Patel",
            "created_date": null,
            "primary_address_id": 0,
            "secondary_address_id": 0,
            "modified_date": null,
            "contact_modified_date": "0000-00-00 00:00:00",
            "created_by": 1
        }

1 个答案:

答案 0 :(得分:0)

它不是json_encode错误。如果你运行下面的代码,你可以看到它会在不到3秒的时间内完成。因为你向用户显示的输出大小和渲染时间。你可以分页你的输出而不是一起展示所有这些

<?php
$str = [];
for($i = 0;$i<4000;$i++){
    $str[] = "sample data";
}
$json = json_encode($str);

echo strlen($json);