How to get remote JSON or XML API data from PHP and assign return object to PHP variable?

What am I doing:

I am writing a user program in PHP that retrieves data through an API from an online LMS service. Right now I'm trying to implement the available SSO features.

This part of the program should execute a GET request for the API when the button is clicked (via js or php POST or?) And ultimately redirect the user's browser to the URL provided in the API response.

The API allows you to select an XML or JSON response, and I would prefer to use JSON, but will use XML if necessary.

From the API documentation when making requests:

All requests listed in this document should contain the content type (XML or JSON) in the request header and have the prefix of the following Uri base: https://api.example.com/v1.svc

eg. Uri, to get a list of users in XML format, will be:

Content-Type: text / xml

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

Below I am trying to implement:

How to get LoginKey

After you have the user ID that you want to sign, you need to make a GET request / users / {user-id}, which will return information about the User. Included in this is LoginKey, which you can use to redirect a custom browser.

eg.

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

API:

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

<LoginKey> - URL-, , .

API- , . , , , .

.

+5
1

HTML <form> ( AJAX) PHP , :

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
    }

}

JSON, file_get_contents(), JSON URL-, json_decode(), .

, AJAX, URL- PHP , , Javascript window.location.href = '...'

+2

All Articles