【问题标题】:Get JSON object from URL从 URL 获取 JSON 对象
【发布时间】:2013-03-15 02:15:19
【问题描述】:

我有一个返回 JSON 对象的 URL,如下所示:

{
    "expires_in":5180976,
    "access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"
} 

我想从 URL 中获取 JSON 对象,然后是 access_token 值。

那么我怎样才能通过 PHP 来检索呢?

【问题讨论】:

标签: php json


【解决方案1】:
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;

为此,file_get_contents 要求启用 allow_url_fopen。这可以在运行时通过包括:

ini_set("allow_url_fopen", 1);

您也可以使用curl 来获取网址。要使用 curl,您可以使用找到的示例 here:

$ch = curl_init();
// IMPORTANT: the below line is a security risk, read https://paragonie.com/blog/2017/10/certainty-automated-cacert-pem-management-for-php-software
// in most cases, you should set it to true
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, 'url_here');
$result = curl_exec($ch);
curl_close($ch);

$obj = json_decode($result);
echo $obj->access_token;

【讨论】:

  • 对不起,我忘了先说如何从 url 获取这个字符串然后访问 json 对象?
  • 这一行出现错误 echo $obj['access_token'];致命错误:无法在第 22 行的 F:\wamp\www\sandbox\linkedin\test.php 中使用 stdClass 类型的对象作为数组
  • @user2199343 如果要将结果用作数组,请在 json_decode 函数中使用“, true”。例如,请参阅我的答案。
  • file_get_contents('url');引用这个有一个错误
  • 您可以将此行放在顶部ini_set("allow_url_fopen", 1); 以在运行时启用allow_url_fopen
【解决方案2】:
$url = 'http://.../.../yoururl/...';
$obj = json_decode(file_get_contents($url), true);
echo $obj['access_token'];

Php 也可以使用带有破折号的属性:

garex@ustimenko ~/src/ekapusta/deploy $ psysh
Psy Shell v0.4.4 (PHP 5.5.3-1ubuntu2.6 — cli) by Justin Hileman
>>> $q = new stdClass;
=> <stdClass #000000005f2b81c80000000076756fef> {}
>>> $q->{'qwert-y'} = 123
=> 123
>>> var_dump($q);
class stdClass#174 (1) {
  public $qwert-y =>
  int(123)
}
=> null

【讨论】:

  • 我更喜欢所选答案的这个答案,原因有一个,只有解析的 json 可以包含带有破折号字符的索引 ex: {"full-name":"khalil","familiy-name":"任何“}解码为数组将使您保持安全
【解决方案3】:

你可以使用 PHP 的 json_decode 函数:

$url = "http://urlToYourJsonFile.com";
$json = file_get_contents($url);
$json_data = json_decode($json, true);
echo "My token: ". $json_data["access_token"];

【讨论】:

  • 很好的例子,但他的方法被称为json_decode 而不是$json_decode
【解决方案4】:

你需要了解json_decode函数http://php.net/manual/en/function.json-decode.php

给你

$json = '{"expires_in":5180976,"access_token":"AQXzQgKTpTSjs-qiBh30aMgm3_Kb53oIf-VA733BpAogVE5jpz3jujU65WJ1XXSvVm1xr2LslGLLCWTNV5Kd_8J1YUx26axkt1E-vsOdvUAgMFH1VJwtclAXdaxRxk5UtmCWeISB6rx6NtvDt7yohnaarpBJjHWMsWYtpNn6nD87n0syud0"}';
//OR $json = file_get_contents('http://someurl.dev/...');

$obj = json_decode($json);
var_dump($obj-> access_token);

//OR 

$arr = json_decode($json, true);
var_dump($arr['access_token']);

【讨论】:

    【解决方案5】:
    // Get the string from the URL
    $json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452');
    
    // Decode the JSON string into an object
    $obj = json_decode($json);
    
    // In the case of this input, do key and array lookups to get the values
    var_dump($obj->results[0]->formatted_address);
    

    【讨论】:

    • 首选代码块格式和解释性 cmets,特别是如果代码没有直接直接回答问题(在这种情况下有不同的键名等)
    【解决方案6】:
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_URL, 'url_here');
    $result = curl_exec($ch);
    curl_close($ch);
    
    $obj = json_decode($result);
    echo $obj->access_token;
    

    【讨论】:

    • 欢迎来到 StackOverflow!这个问题已经回答过很多次了!请详细说明您的答案有何不同并改进了其他答案,而不是简单地转储一些代码。
    【解决方案7】:

    file_get_contents() 没有从 url 获取数据,然后我尝试了curl,它工作正常。

    【讨论】:

      【解决方案8】:

      我们的解决方案,为响应添加一些验证,因此我们可以确定 $json 变量中有一个格式良好的 json 对象

      $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);
      curl_close($ch);
      if (! $result) {
          return false;
      }
      
      $json = json_decode(utf8_encode($result));
      if (empty($json) || json_last_error() !== JSON_ERROR_NONE) {
          return false;
      }
      

      【讨论】:

        【解决方案9】:

        我的解决方案仅适用于以下情况: 如果您将多维数组误认为是单个数组

        $json = file_get_contents('url_json'); //get the json
        $objhigher=json_decode($json); //converts to an object
        $objlower = $objhigher[0]; // if the json response its multidimensional this lowers it
        echo "<pre>"; //box for code
        print_r($objlower); //prints the object with all key and values
        echo $objlower->access_token; //prints the variable
        

        我知道答案已经得到解答,但是对于那些来这里寻找东西的人,我希望这可以帮助你

        【讨论】:

          【解决方案10】:

          当您使用curl 时,有时会给您 403(禁止访问) 通过添加此行来模拟浏览器解决。

          curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)');
          

          希望这对某人有所帮助。

          【讨论】:

            【解决方案11】:
            $curl_handle=curl_init();
            curl_setopt($curl_handle, CURLOPT_URL,'https://www.xxxSite/get_quote/ajaxGetQuoteJSON.jsp?symbol=IRCTC&series=EQ');
            //Set the GET method by giving 0 value and for POST set as 1
            //curl_setopt($curl_handle, CURLOPT_POST, 0);
            curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "GET");
            curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
            curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
            $query = curl_exec($curl_handle);
            $data = json_decode($query, true);
            curl_close($curl_handle);
            
            //print complete object, just echo the variable not work so you need to use print_r to show the result
            echo print_r( $data);
            //at first layer
            echo $data["tradedDate"];
            //Inside the second layer
            echo $data["data"][0]["companyName"];
            

            有时你可能会得到 405,请正确设置方法类型。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2016-05-14
              • 2020-05-11
              • 2021-07-05
              • 2016-12-25
              • 1970-01-01
              • 2016-11-16
              相关资源
              最近更新 更多