-2

How can i get contnts from url Text or Json Format

i am trying to get shortened url created using api link, i am using to methods to get result url, Test and Json. but Bot are not workig for me. Can someone help in this regards.

My Code Using Text Format

$apilink="https://bitcoinly.in/api?api=API-KEy";
$toshort="https://anysite.com/links/verify";
$links = "$apilink&url=$toshort&format=text";
$lines = file($links);
$link= $lines[0];
echo $link;

Using Json Format

$links = "$apilink&url=$toshort&format=json";
$json = file_get_contents($links); 
$data = json_decode($json,true);

$link = $data['shortenedUrl'];
echo $link;
  • 1
    "Isn't working" isn't descriptive enough. Please tell us what is happening, and ideally what you already attempted to do to fix it / figure it out. – Jeto Oct 12 '20 at 04:57
  • it shows nothing. – Khan Gormani Oct 12 '20 at 04:59
  • First things first, did you [properly enable error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display) on your development env? I doubt those snippets would just not produce any output. – Jeto Oct 12 '20 at 05:00
  • yes, ```error_reporting(E_ALL);``` but no error found. – Khan Gormani Oct 12 '20 at 05:08
  • 1
    Did you also do `ini_set('display_errors', 1);` (or enable it through php.ini)? Alternatively, did you check the log files? The only other explanation is that those URLs just simply return an empty response. – Jeto Oct 12 '20 at 05:21
  • Please also do a `var_dump($json);` to see what the API returns before you try and decode it as json. You can also check the [response headers](https://www.php.net/manual/en/reserved.variables.httpresponseheader.php) to see if you get more clues. – Magnus Eriksson Oct 12 '20 at 05:44
  • API Returs ```bool(false)``` – Khan Gormani Oct 12 '20 at 06:14
  • file_get_contents() will return false when it fails (as per the manual). Normally there should be an error or warning logged giving you a clue as to why it failed. – ADyson Oct 12 '20 at 06:48

1 Answers1

0

your code seems to be right.. does your server have file_get_contents() on? if it is on then it will work

<?php
$api = "YOUR_API_KEY";
$url = "yourdestinationlink.com";
$data = json_decode(file_get_contents("https://bitcoinly.in/api?api=$api&url=$url&format=json"), true); 
//initialize link value in the variable
$link = $data['shortenedUrl'];
echo $link;
?>
Nalin Nishant
  • 372
  • 2
  • 15