【问题标题】:Getting http status code from file_get_contents inside helper function从辅助函数中的 file_get_contents 获取 http 状态码
【发布时间】:2018-05-09 21:17:00
【问题描述】:

我有一个自定义帮助函数 (Codeigniter 3),我创建了一个 url,将该 url 传递给 file_get_contents() 函数,然后将所有内容包装到 json_decode() 函数中并将其返回给我的 controller加载要处理的view。这是函数:

function get_json($zipcode) {
    $api_key = KEY;
    $url = 'https://example.com/request.json?api_key=' . $api_key . '&address=' . $zipcode;

    return json_decode(file_get_contents($url), true);
    }

我在这里的控制器中调用它:

$this->load->helper('functions_helper');
$data['json'] =  get_json($data['zipcode']);

然后我根据返回的数据在我的view 中构建一个表:

<?php if (isset($json)) : ?>
    <?php if ($json['metadata']['resultset']['count'] == 0 || http_response_code() == 400): //response code doesn't work ?>

        <div class="inline-block">
            <h3>We apologize but we couldn't locate any results in your area.</h3>
        </div>

    <?php else : ?>

        <table class="table table-striped table-responsive">
            <!-- table elements -->
        </table>
    <?php endif ?>
<?php endif ?>

只要我的 json api 源正常且可靠,它就可以工作。但是,如果我传递一个不是实际邮政编码的邮政编码值,则 api 将返回以下内容,http 状态代码为 400:

{
   "inputs": {
      "address": "00607"
   },
   "metadata": {
      "version": "2.0.0",
      "resultset": {
         "count": 0
      }
   },
   "status": 400,
   "errors": [
      "Unable to geocode address: 00607"
   ]
}

这打破了我的页面,我在顶部得到了一个 php 错误 failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request,即使我尝试从返回的 json json['status'] 中获取状态

此外,如果 json 源已关闭(http 状态代码 500),我也会得到相同的结果。

我的问题是如何在将函数传递到我的页面之前检查函数中的状态代码?我在上面的页面中构建表格之前尝试过检查,但是我的页面当然给出了状态代码 200,这是 viewcontroller 构建的状态,而不是实际 json 结果的状态。

【问题讨论】:

  • 使用 curl 检索 url,这给您更多的控制权,并允许您在尝试解析响应之前检查状态代码。

标签: php json codeigniter codeigniter-3


【解决方案1】:

正如 Rick 在 cmets 中建议的那样,您应该使用 curl。

function get_json($zipcode) {
    $api_key = KEY;
    $url = 'https://example.com/request.json?api_key=' . $api_key . '&address=' . $zipcode;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result = curl_exec($ch);
    $http_code = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if ($http_code == 200) {
        return json_decode($result, true);
    } else {
        return false;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 2011-10-18
    相关资源
    最近更新 更多