How to GET remote JSON or XML API data from within PHP and assign a return object as PHP variable?

16,634

From a HTML <form>, use a traditional post (not AJAX) to a PHP script that does this:

if(isset($_POST['userid']))
{
    $userId = (int)$_POST['userid'];

    $obj = simplexml_load_file('https://api.xxx.com/v1.svc/users/' . $userId . '?apikey=YOUR_API_KEY&source=sampleapp');

    if($obj && isset($obj->LoginKey))
    {
        $loginKey = $obj->LoginKey;

        header('Location: ' . $loginKey);
    }
    else
    {
        // failed to load the xml
    }

}

If you want to do it with JSON you can use file_get_contents() to get the raw JSON from a URL, then use json_decode() to turn it into an object.

Also, if you want to do it via AJAX, you will have to echo the URL with PHP instead of trying to redirect, then have Javascript do the redirect with window.location.href = '...'

Share:
16,634
aethergy
Author by

aethergy

Updated on June 07, 2022

Comments

  • aethergy
    aethergy almost 2 years

    What I'm doing:

    I'm writing a custom program in PHP which pulls data via API from an online LMS service. Right now, I'm trying to implement the available single-sign-on functionality.

    This part of the program needs to execute a GET request to the API when a button is clicked (via js or php POST or ?) and ultimately redirect the users browser to a URL which is supplied in the response from the API.

    The API allows the choice of an XML or JSON response and I would prefer to use JSON but will make do with XML if needed.

    From the API documentation on making requests:

    All requests listed in this document should contain a content-type (XML or JSON) in the request header and be prefixed with the following base Uri: https://api.example.com/v1.svc

    E.g. The Uri to GET a list of Users in XML format would be:

    Content-Type: text/xml

    GET https://api.example.com/v1.svc/users?apikey=MY-KEY&source=MY-APP

    Below is what I'm trying to implement:

    How to get the a user's LoginKey

    Once you have the user id that you want to sign on you need to make a GET request to /users/{user-id} which will return information about the user. Included in this is a LoginKey which you can use to redirect the user's browser to.

    eg.

    GET https://api.example.com/v1.svc/users/USER-ID?apikey=YOUR_API_KEY&source=sampleapp

    Response from API:

    <User>
      <Id>abc12345678</Id>
      <UserName>[email protected]</UserName>
      <FirstName>Rich</FirstName>
      <LastName>Chetwynd</LastName>
      .....
      <LoginKey>https://demo.example.com/login.aspx?loginkey=xxxzzzyyy777222</LoginKey>
    </User>
    

    The <LoginKey> object data is the URL which I need to ultimately redirect the user's browser to.

    I am new to working with APIs and have tried a ton of methods which I could not get to work before posting. If you know how to accomplish this I would be very grateful if you shared your knowledge.

    Thanks.