尝试使用php curl获取和解析JSON时,额外隐藏的字符

时间:2015-10-02 03:26:14

标签: php json curl

这是我的代码:

$target_url = "http://myserver.localhost/get-questions-json.php?id=".$this->variable;
$ch = curl_init($target_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$assess_json = curl_exec($ch);
curl_close($ch);

echo $assess_json显示:

[
    {
        "id": "345",
        "student": "19172",
        "question": "1031",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "346",
        "student": "19172",
        "question": "1035",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "347",
        "student": "19172",
        "question": "1052",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "348",
        "student": "19172",
        "question": "1053",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    },
    {
        "id": "349",
        "student": "19172",
        "question": "1050",
        "answer": "",
        "submitted": "0",
        "entry": "161235",
        "correct": "0"
    }
]

echo strlen($assess_json)显示4078.如果我将字符串复制并粘贴到PHP中,则表示长度为541。

json_decode($assess_json)NULLjson_decode($pasted_str)为对象。

如果我直接去: http://myserver.localhost/get-questions-json.php?id=,它显示了JSON字符串。代码为echo json_encode($questions);

那么我怎样才能让它正确地检索和解析JSON?

1 个答案:

答案 0 :(得分:0)

编辑:

由于包含了PHP页面,因此字符串中实际存在样式和脚本标记。 我使用以下内容来修复它:

Remove everything within script and style tags

$assess_json = preg_replace('/(<(script|style)\b[^>]*>).*?(<\/\2>)/is', "", $assess_json);