【问题标题】:get single parameter out of json_decode [duplicate]从json_decode中获取单个参数[重复]
【发布时间】:2013-12-17 21:54:57
【问题描述】:

我正在使用YOURLS 创建我自己的 URL 缩短器。以下是我对 api 进行 POST 后得到的输出。

我的问题是我似乎无法只取出 shorturl 参数。

{"url":
  {"keyword":"ODuQT",
   "url":"http:\/\/apple.com.sg",
   "title":"Apple (Singapore)",
   "date":"2013-12-02 16:38:51",
   "ip":"219.74.124.134"
  },
  "status":"success",
  "message":"http:\/\/apple.com.sg added to database",
  "title":"Apple (Singapore)",
  "shorturl":"http:\/\/qez4.me\/ODuQT",
  "statusCode":200
}

我的代码在这里:-

function shortenURL($inputUrl) {
$url = 'http://qez4.me/s/yourls-api.php';
$fields = array('signature' => SHORTURL_SIGNATURE,
                'action' => 'shorturl', 
                'url' => urlencode($inputUrl),
                'format' => 'json');

//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_POST,count($fields));
curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

//execute post
$result = curl_exec($ch);

$json = json_decode($result, true);
echo $json["shorturl"];

}

我也尝试过使用$json->shorturl,但所有这些都是为了输出上面显示的json字符串。

【问题讨论】:

  • 你可以试试print_rvar_dump 的结果吗?
  • @rab print_r 给我{"url":{"keyword":"WaDxG","url":"http:\/\/apple.com.sg","title":"Apple (Singapore)","date":"2013-12-02 16:50:51","ip":"219.74.124.134"},"status":"success","message":"http:\/\/apple.com.sg added to database","title":"Apple (Singapore)","shorturl":"http:\/\/qez4.me\/WaDxG","statusCode":200}1
  • @user1258600 你试过print_r($json) 吗?
  • @rab 两者似乎都返回相同的东西。
  • @user1258600 和 var_dump( $json ); ?

标签: php json yourls


【解决方案1】:

您的代码缺少 cURL 中的“返回传输”选项

$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); //this line

【讨论】:

  • omggggg 我不知道这样的事情存在。非常感谢你,我会去读一下。你解决了我的问题:)
猜你喜欢
  • 2011-02-22
  • 2013-04-09
  • 2014-03-15
  • 2011-07-09
  • 2015-03-11
  • 1970-01-01
  • 2015-02-24
  • 2016-12-23
  • 2014-01-12
相关资源
最近更新 更多