2017-09-06 16 views
-3

我拼湊了一些代碼來使用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>來包裝它,但是把它排成一行......如何格式化這個輸出以便於理解?

+0

你可以做一個json_decode和json_encode用'JSON_PRETTY_PRINT'可用。但這樣做只是爲了發展目的! – Jeff

+0

@Jeff,是的,我只需要將輸出顯示爲格式化的代碼塊。所以當我嘗試:echo json_decode($ response,JSON_PRETTY_PRINT);我的屏幕顯示一個單詞:Array。但是,當我嘗試echo json_encode($ response,JSON_PRETTY_PRINT);我在每個雙引號的前面加上額外的反斜槓.. – santa

回答

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 5.4.0 <

+0

很好,謝謝。 – santa