get single parameter out of json_decode

215 views Asked by At

I am using YOURLS to create my own URL shortener. The below is the output I get after doing a POST to the api.

My problem is I cant seem to get just the shorturl parameter out.

{"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
}

My code is here:-

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"];

}

I have also tried using $json->shorturl but all these do is to output the json string shown above.

1

There are 1 answers

1
Allen Chak On BEST ANSWER

Your code is missing the 'return transfer' option in 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