从json_decode中获取单个参数

时间:2013-12-02 08:47:21

标签: php json yourls

我正在使用YOURLS创建自己的网址缩短器。以下是对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字符串。

1 个答案:

答案 0 :(得分:0)

您的代码缺少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