doupuchen6378 2017-09-06 20:28
浏览 58
已采纳

Prettify响应输出[关闭]

I cobbled together some code to retrieve info using 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;
}

It works fine, however the output seems to be in a single row. I've tried wrapping it with <pre></pre> but got it in a single row... How do I format this output for easier comprehension?

</div>
  • 写回答

1条回答 默认 最新

  • duanju6788 2017-09-06 20:39
    关注

    You can decode and encode with JSON_PRETTY_PRINT the received 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."
        }
    }
    

    Note, that JSON_PRETTY_PRINT is not available in php < 5.4.0

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度