1

I have access to a URL that if i simply put http://example.com/weight into address bar it returns a float number...

Ex: 17.23kg

Image for better understanding:

What happens if i go to URL

My objective is to use PHP for assigning this float value into a variable. $weight = float value...

Here is the code i did with hopes that it would work:

$url = 'http://example.com/weight';
$url_components = parse_url($url);
parse_str($url_components['weight'], $params);
$weight = $params['weight'];
echo $weight;

But this returned nothing...

What am i doing wrong?

jibsteroos
  • 1,366
  • 2
  • 7
  • 13
Raul Chiarella
  • 518
  • 1
  • 8
  • 25
  • 1
    It would return quite a bit if you [enabled error reporting](https://stackoverflow.com/questions/1053424/how-do-i-get-php-errors-to-display). Sorry, I don't know where to start, this code cannot do what you expect it to. For one it doesn't access the URL. See: [file_get_contents()](https://www.php.net/manual/en/function.file-get-contents.php). Please read the PHP manual carefully. – KIKO Software Sep 11 '21 at 20:29
  • Hello! I enabled error logging and it returned 'Index was not found' ... I will take a look into file_get_contents() and see if i can come up with a code that gets the value from the URL entered. – Raul Chiarella Sep 11 '21 at 20:56
  • It's confusing, the image provided suggests that the value you are looking for is in the body of the reply (as image, html or any other possible think) and not int URL itself which is where your code are trying to extract the information. – Ronaldo Ferreira de Lima Sep 11 '21 at 20:59

1 Answers1

2

If you want to retrieve the contents of a url, you can use the file_get_contents() function. The implementation would look something like this:

$url = 'http://example.com/weight';
$weight = file_get_contents($url);
echo $weight;

Also, you might want to use a function like floatval() to convert your result to a float.
Read more about file_get_contents() here: https://www.w3schools.com/php/func_filesystem_file_get_contents.asp

Matt K
  • 104
  • 3