预备响应输出

时间:2017-09-06 20:28:41

标签: php api

我拼凑了一些代码来使用Yelp API检索信息。

$postData = "grant_type=client_credentials&".
    "client_id=MyClientIDl94gqHAg&".
    "client_secret=SomEcoDehIW09e6BGuBi4NlJ43HnnHl4S7W5eoXUkB";


// GET TOKEN
$curl = curl_init();

//set the url
curl_setopt($curl,CURLOPT_URL, "https://api.yelp.com/oauth2/token");
//tell curl we are doing a post
curl_setopt($curl,CURLOPT_POST, TRUE);
//set post fields
curl_setopt($curl,CURLOPT_POSTFIELDS, $postData);
//tell curl we want the returned data
curl_setopt($curl,CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($curl);

if($result){
    $data = json_decode($result);
}

// GET RESTAURANT INFO
curl_setopt_array($curl, array(
    CURLOPT_URL => "https://api.yelp.com/v3/businesses/north-india-restaurant-san-francisco",
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => "",
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 30,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => "GET",
    CURLOPT_HTTPHEADER => array(
        "authorization: Bearer ".$data->access_token
    ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

//close connection
curl_close($curl);

if ($err) {
    echo "cURL Error #:" . $err;
} else {
    echo $response;
}

它工作正常,但输出似乎是一行。我已经尝试用<pre></pre>包装它但是把它放在一行......我如何格式化这个输出以便更容易理解?

1 个答案:

答案 0 :(得分:1)

您可以使用JSON_PRETTY_PRINT对收到的json进行解码和编码:

$a='{"error": {"code": "TOKEN_MISSING", "description": "An access token must be supplied in order to use this endpoint."}}';
$b=json_decode($a);
$c=json_encode($b, JSON_PRETTY_PRINT);
echo "<pre>".$c."</pre>";

// result:

{   
    "error": {   
        "code": "TOKEN_MISSING",
        "description": "An access token must be supplied in order to use this endpoint."
    }
}

注意,JSON_PRETTY_PRINT在php&lt; 5.4.0