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

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

报告相同问题?

悬赏问题

  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录