PHP get results from URL

10,440

Solution 1

Just make a request to your API service:

$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result = file_get_contents($url);

Then, if I understand correctly, your API returns JSON response, so you have to decode it:

$vars = json_decode($result, true);

Which will return an array with all the variables:

echo $vars['firstname']; //"John";
echo $vars['Surname']; //"Smith";

Solution 2

solution: file_get_contents (or maybe you'll need curl if ini_get("allow_url_fopen") !=1 ....)

$url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
$result=parse(file_get_contents($url));
print_r($result);

hope your "parse()" function knows how to parse the result from your api call. i guess you don't know what you're doing, and next you'll be asking why the parse function is not defined :p (it looks like you're looking for json_decode , just a guess.)

i think your parse function would look like:

function parse($apiresponse){return json_decode($apiresponse,true);}
Share:
10,440
Smudger
Author by

Smudger

Updated on June 04, 2022

Comments

  • Smudger
    Smudger almost 2 years

    stupid question I think.

    I have an API that i want to access. if I simply put the url in my browser it returns all the results correctly.

    https://api.mydomain.com/v1/name?user=user1&pass=1234
    

    in my browser this returns array information:

    {"firstname":"John","Surname":"Smith"}    
    

    I want to be able to use PHP to simply assign the results of the URL page to a variable:

    $url="https://api.mydomain.com/v1/name?user=user1&pass=1234";
    $result=parse($url);
    print_r($result);
    

    This obviously doesnt work but just looking for the correct syntax. done some research but not getting any luck. should be so simple but is not.

    advice appreciated as always. Thanks