RESTFUL web service response parsing issue - php

I am getting the restful web service response as well. But I am not able to parse it properly
my code looks like this
include 'RestClient.class.php';
error_reporting(E_ALL);
// Client Profile
$url = "http://localhost/lgen/index.php/api/client";
$ex = RestClient::get($url,array('requestType' =>'viewClientProfile',
'username' => 'uname',
'pass' =>'pass'));
echo $response = $ex->getResponse();
$xml = simplexml_load_string($response);
when print $response I am getting data on browser but while trying to parse it am not getting any kind of data

echo $response = $ex->getResponse();
You are creating and echoing a variable at the same time.
Try this:
$xml = simplexml_load_string($ex->getResponse());
var_dump($xml);

Related

How do I get a POD image from an API call

I am calling an API of a shipping company to get the POD (Proof of delivery) image of a delivery as per this document.
I am expecting to see an image but the the API response is null.
Here is my code:
$host = "api.shiplogic.com";
$accessKey = 'AKIA55D5DNTBI4X24BCM'; //Sandbox credentials
$secretKey = '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'; //Sandbox credentials
$requestUrl = 'https://api.shiplogic.com';
$uri = '/shipments/pod/images?';
$httpRequestMethod = 'GET';
$data = 'tracking_reference=';
$refnr = 'FQJNF'; //created for testing
require 'AWS/aws-autoloader.php';;
use Aws\Signature\SignatureV4;
use Aws\Credentials\Credentials;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use Psr\Http\Client\ClientInterface;
$signature = new SignatureV4('execute-api', 'af-south-1');
$credentials = new Credentials($accessKey, $secretKey);
$psr7Request = new Request($httpRequestMethod, $requestUrl.$uri.$data.$refnr);
$client = new Client([$requestUrl, 'timeout' => 30]);
$sr = $signature->signRequest($psr7Request, $credentials);
$response = $client->send($sr);
$json = $response->getBody()->getContents();
echo $json;
I have tried to var_dump() and print_r()
What am I missing or doing wrong?
[{"id":203913730,"parcel_id":0,"date":"2022-08-05T09:44:19.704Z","status":"delivered","source":"danieladmin","message":"POD file(s) captured","data":{"images":["https://shiplogic-backend-prod-infra-images-and-notes.s3.af-south-1.amazonaws.com/shipment-images/8155533-fe1e0e10-324c-4360-b2f4-be51f091f8b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hgfug0TnycpXSg1bAOQ5ROelqQi5kcuy%2FTT3tePuZy1EO%2BXTm0tQbE3tf0XkLw34cQ6078ZAQJ7tyI4R4qRnWfdTkLtM\u0026X-Amz-SignedHeaders=host\u0026X-Amz-Signature=9a3d73a886012ac24e4719888156922d840a73d43569934a8de33ab2336f47b1"]}}]
<Error>
<Code>AuthorizationQueryParametersError</Code>
<Message>
X-Amz-Algorithm only supports "AWS4-HMAC-SHA256 and AWS4-ECDSA-P256-SHA256"
</Message>
<RequestId>ECGG4HGD86Y0PYAY</RequestId>
<HostId>
qZHFwL8gZ3GEibJ6UmgAoNd97EMVGe1Xw24RjYIKAqqrOi2Cx+YPmBJGoCy4opTiih5Nz5YlEuU=
</HostId>
</Error>
Your code is actually entirely correct as far as getting the response, but the problem is that the response you're trying to copy the URL from is still JSON encoded. This leaves some of the parts of the URL in an invalid, encoded state; specifically, the & is encoded to /u0026.
...?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026...
That /u0026 at the end of each parameter is the culprit. If you json_decode() the response, then you get the correct URL.
The URL I received when I ran the code and decoded the result seems to work. All I did was add a line and change the last line:
...
$json = $response->getBody()->getContents();
$result = json_decode($json, false);
echo $result[0]->data->images[0];
You could obviously do that without adding a line and just changing the line where $json is assigned, but I wanted to leave that line alone to make it easier to see exactly what was different.
...
$json = json_decode($response->getBody()->getContents(), false);
echo $json[0]->data->images[0];

Returning value from restAPI in php, echo value not showing

I'm trying to return a value from my API using PHP, api can be found here:
code is as follows:
Im not seeing the echo on my page, don't see any errors and I believing im reading the json in correctly. Any help appreciated!
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue["Age"];
?>
From what I can tell, the json is not valid on the server side (due to the "connected to db" text in front of the {} part). I think it would be a good idea to fix the server side response json data, if possible!
For now, here is a way to get the value it looks like you are intending to retrieve:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$adjusted_response = str_replace('connected to db', '', $response);
$returnvalue = json_decode($adjusted_response, true);
echo $returnvalue['tv_shows']['Age'];
?>
Output:
$ php example.php
16+
If the server side json data is fixed, I think you could shorten the code to something like this:
<?php
$titleid = 2;
$url = "http://kmoffett07.lampt.eeecs.qub.ac.uk/serverSide/buildapi.php?id={$titleid}";
$response = file_get_contents($url);
$returnvalue = json_decode($response, true);
echo $returnvalue['tv_shows']['Age'];
?>
The thing is that $response is returned as string , in order to fix that you need to edit your backend and make it give the response without "connected to db"

Parsing of a XML response

I am completely new to XML.
I have a URL which gives me a XML response. I am facing problems in parsing the response and showing only the details that I want. Currently the url is "https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E"
and I am using the following code:
$feed = file_get_contents($url);
$items = simplexml_load_string($feed);
print_r($items);
and this was the error
file_get_contents( https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3EAmsterdam%3C%2Fcity%3E%3CarrivalDate%3E08/30/2014%3C%2FarrivalDate%3E%3CdepartureDate%3E08/31/2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E1%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E): failed to open stream: Invalid argument
I have also tried using simplexml_load_file() and it's showing the same error.
file_get_contents on the URL is returning content of type json, that's why simple_xml_load_file cannot parse it. Use this
$feed = file_get_contents("https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E");
//echo $feed;
$json = json_decode($feed);
print_r($json);
Currently when viewed on the browser its an xml but in the script is responds a json.
$url = 'https://api.eancdn.com/ean-services/rs/hotel/v3/list?cid=55504&minorRev=99&apiKey=cbrzfta369qwyrm9t5b8y8kf&locale=en_US&currencyCode=USD&xml=%3CHotelListRequest%3E%3Ccity%3ESeattle%3C%2Fcity%3E%3CstateProvinceCode%3EWA%3C%2FstateProvinceCode%3E%3CcountryCode%3EUS%3C%2FcountryCode%3E%3CarrivalDate%3E%3C%2FarrivalDate%3E%3CdepartureDate%3E9%2F1%2F2014%3C%2FdepartureDate%3E%3CRoomGroup%3E%3CRoom%3E%3CnumberOfAdults%3E2%3C%2FnumberOfAdults%3E%3C%2FRoom%3E%3C%2FRoomGroup%3E%3CnumberOfResults%3E25%3C%2FnumberOfResults%3E%3C%2FHotelListRequest%3E';
$contents = file_get_contents($url);
$data = json_decode($contents, true);
// becomes an array

Using cURL with wunderground api

Hey I'm having some issues using cURL (I can't use file_get_contents because my web host won't allow it) to access parts of the wunderground weather api.
When I use the following code to access info on weather conditions I have no issues whatsoever:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/geolookup/conditions
/q/IA/Cedar_Rapids.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$parsed_json = json_decode($result);
$location = $parsed_json->{'location'}->{'city'};
$temp_f = $parsed_json->{'current_observation'}->{'temp_f'};
echo "Current temperature in ${location} is: ${temp_f}\n";
?>
However, when I make slight modifications in order to get data on high and low tides using the following code I get nothing:
<? $json_url = 'http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json';
// jSON String for request
$json_string = '[http://api.wunderground.com/api/b2b4a1ad0a889006/tide/q/NJ/Wildwood.json]';
// Initializing curl
$ch = curl_init( $json_url );
// Configuring curl options
$options = array(
CURLOPT_RETURNTRANSFER => true,
);
// Setting curl options
curl_setopt_array( $ch, $options );
// Getting results
$result = curl_exec($ch); // Getting jSON result string
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
?>
Now I know the issue may be that I'm dealing with an array in the second example but I'm not sure how to modify the code. I know that the record for the first low tide is [3] and I've tried making the following modification with no luck.
$tide_time = $parsed_json->{'tide'}->{'tideSummary'}->[3]->{'date'}->{'pretty'};
echo "High tide is at ${tide_time} ";
Any help would be greatly appreciated!
The second parameter of json_decode allows you to decode the JSON into an array instead of an object. Try turning that on so you always know what you're dealing with:
$response = json_decode($result, true);
If that fails maybe you're not using the API correctly?

need php api help

hi friends i am trying to solve how i can access the halo reach api for get states bungie has released a api for this here is the link http://www.bungie.net/fanclub/statsapi/Group/Resources/Article.aspx?cid=545064
how can i access this service via php and display some stats need help thanks
i am trying like this
<?php
require_once('lib/nusoap.php');
$wsdl = "http://www.bungie.net/api/reach/ReachApiJson.svc?wsdl";
$client = new soapclient($wsdl, 'wsdl');
$parameters['parameters']['apikey'] = "xxx";
$result = $client->call("GetGameMetadata", $parameters);
?>
Consuming JSON in PHP is pretty simple.
<?PHP
$uri = 'http://www.bungie.net/api/reach/reachapijson.svc/game/metadata/xxx';
if (! $json = file_get_contents($uri)){ //cURL can be faster and more flexible, but this ought to work
trigger_error('API call failed!');
}
if (! $result = json_decode($json)){
trigger_error('API returned bad data?');
//maybe log some stuff here, so you can debug.
}
print_r($result); //see what you got.

Categories