REST call to a URL list, return JSON values into a table

I am looking for an example, or a link to a working example of this arrangement:

You place RESTful call for certain values to a URL which is a JSON list, generated by an API, then - return
those JSON values and display in a generated table. I hope that I have explained this well enough.

Thank you for looking at this Post and I appreciate your help in pointing me in the right direction!

Here is a simple way to do this, just threw it together so there might be some problems. I’ve ran it against the services in the code and it seems to work as expected :slight_smile:

restCall.php
[php]<?php

class restCall {

private $url;
private $port;

public function __construct($url = ‘’, $port = 80) {
if (!function_exists(‘curl_init’)) {
throw new Exception(‘Sorry cURL is not installed!’);
}

  $this->url = $url;
  $this->port = $port;

}

public function call($call = ‘’, $type = ‘json’) {
$return = false;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $this->url . $call);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);

  $response = curl_exec($ch);

  if (!$response) {
     throw new Exception('Error while calling api');
  }

  switch ($type) {
     case 'json':
        $return = json_decode($response);
        break;
     case 'xml':
        $return = simplexml_load_string($response);
        break;
     default:
        throw new Exception('API calls of this type is not implemented');
        break;
  }

  return $return;

}

public function setUrl($url = ‘’) {
$this->url = $url;
}

public function setPort($port = 80) {
$this->port = $port;
}

}[/php]

demo.php
[php]<?php

try {
require_once ‘restCall.php’;

$jsonTest = new restCall(‘https://graph.facebook.com/’);
$response = $jsonTest->call(4); // try your facebook ID (or profile name) here

/*
* At this point we have an object with the response from facebook. Uncomment
* the following code to display the response
*/
// echo ‘Response from jsonTest:

’;
// var_dump($response);
// echo ‘
’;

?>

JSON Demo

<?php

$xmlTest = new restCall(‘http://api.openweathermap.org/data/2.5/weather?q=’);
$response = $xmlTest->call(‘London&mode=xml’, ‘xml’);

/*
* At this point we have an object with the response from open weather. Uncomment
* the following code to display the response
*/
// echo ‘Response from xmlTest:

’;
// var_dump($response);
// echo ‘
’;

?>

XML Demo

    <?php foreach ($response->temperature->attributes() as $key => $value) { ?>
  • Attribute key: <?= $key ?>
  • Attribute value: <?= $value ?>
  • <?php } ?>
<?php

} catch (Exception $e) {
echo 'Error: ’ . $e->getMessage();
}
[/php]

Hi Jim! thanks for the example! I appreciate your quick reply - I am now studying the code. Thank you! I see
that the results end up in a list… I will try to add a dynamic table instead…

I might have a question or two later… :slight_smile:

(also, not to be a pest or an overbearing ass, but - other links or examples are welcome as well…)

Just do a google search for “php curl json”, it is a popular combo so you will get thousands of examples/tutorials to choose from :slight_smile:

Thank you! I understand that cURL is a method, not an extra component to be installed? I just googled
some examples… I will go ahead and do some reading on the subj and maybe throw together a test
arrangement now… - thanks again!

curl is an extension that will have to be installed/working on your hosting environment to be available. If it is then PHP comes with quite a few functions (library) to be able to use curl to connect and communicate with other servers.

You can read more here: http://www.php.net/manual/en/intro.curl.php

I would probably change my code to move the type variable into the construct instead of sending it in with each call

restCall.php
[php]<?php

class restCall {

private $url;
private $port;
private $type;

public function __construct($url = ‘’, $port = 80, $type = ‘json’) {
if (!function_exists(‘curl_init’)) {
throw new Exception(‘Sorry cURL is not installed!’);
}

  $this->url = $url;
  $this->port = $port;
  $this->type = $type;

}

public function call($call = ‘’) {
$return = false;

  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $this->url . $call);
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_TIMEOUT, 10);

  $response = curl_exec($ch);

  if (!$response) {
     throw new Exception('Error while calling api');
  }

  switch ($this->type) {
     case 'json':
        $return = json_decode($response);
        break;
     case 'xml':
        $return = simplexml_load_string($response);
        break;
     default:
        throw new Exception('API calls of this type is not implemented');
        break;
  }

  return $return;

}

public function setUrl($url = ‘’) {
$this->url = $url;
}

public function setPort($port = 80) {
$this->port = $port;
}

}[/php]

demo.php
[php]<?php

try {
require_once ‘restCall.php’;

$jsonTest = new restCall(‘https://graph.facebook.com/’);
$response = $jsonTest->call(4);
$anotherUser = $jsonTest->call(5);

/*
* Or we could get multiple
*/
$users = array();
$userIds = array(7,10,11,13,27,28,29);
foreach ($userIds as $userId) {
$users[] = $jsonTest->call($userId);
}

?>

First fetch

Another user

Userlist

    <?php foreach ($users as $user) { ?>
  • Name: <?= $user->name ?>
  • Link: <?= $user->link ?>
  • <?php } ?>
<?php

/*
* You can continue to make calls here as well
*/
$user3 = $jsonTest->call(‘jimleirvik’); //etc…

} catch (Exception $e) {
echo 'Error: ’ . $e->getMessage();
}
[/php]

Output:

[code]First fetch

Name: Mark Zuckerberg
Link: http://www.facebook.com/zuck

Another user

Name: Chris Hughes
Link: http://www.facebook.com/ChrisHughes

Userlist

Name: Arie Hasit
Link: http://www.facebook.com/arie.hasit
Name: Marcel Laverdet
Link: http://www.facebook.com/marcel
Name: Soleio
Link: http://www.facebook.com/soleio
Name: Chris Putnam
Link: http://www.facebook.com/putnam
Name: Colin Kelly
Link: http://www.facebook.com/improvite
Name: Mark Kaganovich
Link: http://www.facebook.com/kaganovich
Name: Andrei Boros
Link: http://www.facebook.com/andrei.boros.3

[/code]

Output:

— hehe, - I see you got it working?!

It was always working :slight_smile:

  • what I did, to try out the action, I actually used your example on the page and got an error “Error: Error while calling api”… but this is not a problem, although I do not know what caused it :slight_smile: - the call/answer is triggered
    by entering the page, how would you trigger the call with something pushable :slight_smile: - like a button or a form on submit? I do not need the actual creation of the code - at least point in the right direction on how to do it, if you can?

You could add some error reporting to the curl call so you can see what goes wrong :slight_smile:

But in your case you should look into doing ajax calls with javascript, no need to include php in the task you describe.

This should get you started: http://api.jquery.com/jQuery.post/

First - thanks for your advice, I’ll look into both methods.

Second - my situation is that the page is a part of a PHP-based CMS, so to use PHP/REST/JSON solution seemed to be a reasonable way to proceed.

In most projects you will end up mixing server side and client side to make your site. If you want an action to run on an user triggered event then javascript is the obvious choice, simply because the user will not have to go through “the pain” of the page reloading in order to get the wanted data.

You can obviously make a simple api yourself and use javascript to catch the button click event and send a post request to your api. Your api can in turn use php/curl/json/sql/whatever to fetch data and form the output. But since you can send a request directly from javascript it’s kinda unnecessary.

Or you can use a link/button to redirect the user to somesite.php?id=someid and then use curl to fetch that id and present it to the user :slight_smile:

that’s the beauty of programming, it is up to you!

Here is the example (that does not work BTW ;D) from the web that looks very close to what I want to get -
there’s a REST/cURL call and JSON data returned and place into the table:

[php]<?php
$url = ‘http://173.36.21.72:8777/v2/meters/disk.read.bytes’;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [‘X-Auth-Token: Example’]);
$result = curl_exec($ch);
$data = json_decode($result,true);
curl_close($ch);
?>

<?php echo ''; echo ''; $n = 0; foreach ($data as $key => $jsons) { foreach ($jsons as $key => $value) { echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; $n++; } } echo '
Username Period Room Next?
'.$data[$n]['counter_name'].''.$data[$n]['user_id'].''.$data[$n]['resource_id'].''.$data[$n]['timestamp'].''.$data[$n]['resource_metadata'].'
'; ?>[/php]

Any suggestions?

I can’t get a response from the server so it’s hard to know, but this should give you the error:

[php]<?php

$url = ‘http://173.36.21.72:8777/v2/meters/disk.read.bytes’;

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [‘X-Auth-Token: Example’]);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$result = curl_exec($ch);

if (!$result) {
echo 'Curl error: ’ . curl_error($ch);
die();
}

$data = json_decode($result, true);
curl_close($ch);

echo ‘

’;
echo ‘’;

$n = 0;

foreach ($data as $key => $jsons) {
foreach ($jsons as $key => $value) {
echo ‘

’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
echo ‘’;
  echo '</tr>';

  $n++;

}
}
echo ‘

Username Period Room Next?
’ . $data[$n][‘counter_name’] . ‘’ . $data[$n][‘user_id’] . ‘’ . $data[$n][‘resource_id’] . ‘’ . $data[$n][‘timestamp’] . ‘’ . $data[$n][‘resource_metadata’] . ‘
’;[/php]
  • yes, I see the changes, and I will try this live with the actual url - thanks for the follow-up!

P.S.: - it’s sending the request fine, so I’ll work on this version in more detail! thanks a bunch!!

So, I changed a few things in the code above and came up with this:

<?php $url = 'http://domain.com/1.0/parts/parts?categoryGroupID=1'; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, ['X-Auth-Token: Example']); curl_setopt($ch, CURLOPT_TIMEOUT, 10); $result = curl_exec($ch); if (!$result) { echo 'Curl error: ' . curl_error($ch); die(); } $data = json_decode($result, true); curl_close($ch); echo ''; echo ''; $n = 0; foreach ($data as $key => $jsons) { foreach ($jsons as $key => $value) { echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; echo ''; $n++; } } echo '
Part Number Description Status Timestamp Datasheet
' . $data[$n]['PartNumber'] . '' . $data[$n]['Description'] . '' . $data[$n]['Status'] . '' . $data[$n]['Timestamp'] . '' . $data[$n]['Datasheet'] . '
'; It pretty much describes what I want to do. At this point, the script brings back raw JSON from the URL ad displays it on the page and then creates an empty table below raw JSON. It also produces this this warning: "Warning: Invalid argument supplied for foreach() in eval()... "... it is obvious, that the engine to choose items for display in the table is missing - it would be nice to get specific values into the appropriate s and this script does not have that engine to do it yet...

Post the json data as well (the {…} string). That way I can simulate getting an response and see what you’re doing wrong when trying to display it

Sponsor our Newsletter | Privacy Policy | Terms of Service