I am ignorant when it comes to SOAP. I am performing a web service call:
<?php
// define the SOAP client using the url for the service
$client = new soapclient('http://www.xignite.com/xMetals.asmx?WSDL', array('trace' => 1));
// create an array of parameters
$param = array(
'Type' => "XAU",
'Currency' => "USD");
// call the service, passing the parameters and the name of the operation
$result = $client->GetLastRealTimeMetalQuote($param);
// assess the results
if (is_soap_fault($result)) {
echo '<h2>Fault</h2><pre>';
print_r($result);
echo '</pre>';
} else {
echo '<h2>Result</h2><pre>';
print_r($result);
echo '</pre>';
}
?>
and when I run the script i get:
Result
stdClass Object
(
[GetLastRealTimeMetalQuoteResult] => stdClass Object
(
[Outcome] => Success
[Identity] => IP
[Delay] => 0.006
[Symbol] => XAUUSDO
[Type] => XAU
[Currency] => USD
[Date] => 8/1/2011
[Time] => 11:18:48 PM
[Rate] => 1618.88500977
[Bid] => 1618.55004883
[BidTime] => 11:18:48 PM
[Ask] => 1619.2199707
[AskTime] => 11:18:48 PM
)
)
How do I separate the [Bid] out from the rest of the result and store it in a variable.
Or better yet how can I pull out the array?
Don't let the stdClass object mix you up - this is simply an array that is represented with object notation. So, $result['GetLastRealTimeMetalQuoteResult']['Bid'] (a normal associative array) becomes $result->GetLastRealTimeMetalQuoteResult->Bid - same values, just a different notation.
You get stdClass objects when a value is typecast into an object, which the SOAP library does. See: http://php.net/manual/en/reserved.classes.php For some more detail about stdClass, check out this article: http://krisjordan.com/dynamic-properties-in-php-with-stdclass
If you'd like to convert the stdClass to an array, unfortunately you'll have to use a little function:
function objToArray($obj=false) {
if (is_object($obj))
$obj= get_object_vars($obj);
if (is_array($obj)) {
return array_map(__FUNCTION__, $obj);
} else {
return $obj;
}
}
$somevar = $result->GetLastRealTimeMetalQuoteResult->Bid;
Related
CoinGate\Merchant\Order Object
(
[order:CoinGate\Merchant\Order:private] => Array
(
[id] => 97977
[status] => new
[do_not_convert] =>
[price_currency] => USD
[price_amount] => 1200.0
[lightning_network] =>
[receive_currency] => EUR
[receive_amount] =>
[created_at] => 2018-07-03T05:53:43+00:00
[order_id] => 459469
[payment_url] => https://sandbox.coingate.com/invoice/94423345-1a1a-4895-a08e-98793777b0d0
[token] => x5Yrx5mmku8nkyK2ShVvbCuiJfasoxsNBtxZ27Ra
)
)
This is response of request but i am facing to get values from such array. I need to get payment_url from such array.
In a Order.php file there's a magic __get method. So, you should use it to get the property you need:
// suppose $response is the value you `var_dump`ed in a question.
echo $response->payment_url; // same for other properties: $response->status
get_object_vars function in PHP convert object to array. Consider you are having this object in variable $x, then you should do like:
$y = get_object_vars($x);
echo $y['payment_url'];
I have installed Geocoder following the instructions here: https://github.com/geocoder-php/Geocoder
And then I try to run this example:
require __DIR__.'/vendor/autoload.php';
$bingApikey = 'xxxxxxxxxxxxxxxxxxxxxxx';
$curl = new \Ivory\HttpAdapter\CurlHttpAdapter();
$geocoder = new \Geocoder\Provider\BingMaps($curl,$bingApikey);
$result = $geocoder->geocode('Μπουμπουλίνας 1, 155 62 Χολαργός Αττικής');
When I try to var_dump the $result I get an error:
<b>Catchable fatal error</b>: Object of class Geocoder\Model\AddressCollection could not be converted to string in <b>C:\MAMP\htdocs\Wind\geocoding\geocodeCheck.php</b> on line <b>21</b><br />
What am I doing wrong?
this documentation is pretty bad.. to get data to return in a format i could use i had to use a dumper call along with a json decoder. there are a variety of dumpers included in the source and you need to make sure that when you call them your call is case sensitive (look in the source you downloaded for the proper dumper names and the examples the author gives wont work if you just cut and paste).
here is how i got things to work:
require 'vendor/autoload.php';
$curl = new \Ivory\HttpAdapter\CurlHttpAdapter();
$geocoder = new \Geocoder\Provider\GoogleMaps($curl);
$data = $geocoder->geocode("1600 Pennsylvania Ave Washington DC")->first();
$dumper = new \Geocoder\Dumper\GeoJson();
$jsondata = $dumper->dump($data);
$decoded = json_decode($jsondata);
print_r ($decoded->{'geometry'}->{'coordinates'});
the end result of the json array gives me the lat and long
Array
(
[0] => -76.9818437
[1] => 38.8791981
)
if you print out the whole decoded array you get all the following.
stdClass Object
(
[type] => Feature
[geometry] => stdClass Object
(
[type] => Point
[coordinates] => Array
(
[0] => -76.9818437
[1] => 38.8791981
)
)
[properties] => stdClass Object
(
[streetNumber] => 1600
[streetName] => Pennsylvania Avenue Southeast
[postalCode] => 20003
[locality] => Washington
[adminLevels] => stdClass Object
(
[1] => stdClass Object
(
[name] => District of Columbia
[code] => DC
)
)
[country] => United States
[countryCode] => US
)
[bounds] => stdClass Object
(
[south] => 38.8791981
[west] => -76.9818437
[north] => 38.8791981
[east] => -76.9818437
)
)
hope this helps
From the docs:
Both geocode() and reverse() methods return a collection of Address objects
first() retrieves the first Address;
https://github.com/geocoder-php/Geocoder#address--addresscollection
Try
$result = $geocoder->geocode('Μπουμπουλίνας 1, 155 62 Χολαργός Αττικής')->first();
Based only on documentation (therefore limited), something else to try:
$result = $geocoder->geocode('Μπουμπουλίνας 1, 155 62 Χολαργός Αττικής');
if($result->count() > 0) {
echo $result->first();
}
else {
echo 'no result';
}
I'm also assuming you can do something like this:
$result = $geocoder->geocode('Μπουμπουλίνας 1, 155 62 Χολαργός Αττικής');
for($i=0; $i<$result->count(); ++$i) {
echo $result->get($i);
}
This is all speculation though, as the documentation is lacking in details and I don't have this package installed to test it.
I get an object with nested arrays of nested objects when I make an API call. In the SDK I have the header set to accept: application/json. I am wondering why I am getting objects and arrays back?
Here is a partial part of the response:
PayPal\Api\CreditCard Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[type] => amex
[number] => xxxxxxxxxxx0005
[expire_month] => 5
[expire_year] => 2015
[cvv2] => 1234
[first_name] =>
[last_name] =>
[payer_id] => 3zIVtTFQ7UdKjP5mssjtzoUo6NvrsExl466oPC4Mm8nwOjI6BS
[id] => CARD-35X96613EN689504VKKCA4RA
[state] => ok
[valid_until] => 2015-06-01T00:00:00Z
[create_time] => 2013-11-13T23:41:56Z
[update_time] => 2013-11-13T23:41:56Z
[links] => Array
(
[0] => PayPal\Api\Links Object
(
[_propMap:PayPal\Common\PPModel:private] => Array
(
[href] => https://api.sandbox.paypal.com/v1/vault/credit-card/CARD-35X96613EN689504VKKCA4RA
[rel] => self
[method] => GET
)
)
[1] => PayPal\Api\Links Object
... and so on
Code that creates this
public static function get($creditCardId, $apiContext = null) {
if (($creditCardId == null) || (strlen($creditCardId) <= 0)) {
throw new \InvalidArgumentException("creditCardId cannot be null or empty");
}
$payLoad = "";
if ($apiContext == null) {
$apiContext = new ApiContext(self::$credential);
}
$call = new PPRestCall($apiContext);
print_r($call);
die;
$json = $call->execute(array('PayPal\Rest\RestHandler'), "/v1/vault/credit-card/$creditCardId", "GET", $payLoad);
$ret = new CreditCard();
$ret->fromJson($json);
return $ret;
}
Ok, so thank you Machavity for the help. The issue was that in the function that I posted above, it takes the JSON response and converts it to some wierd object thing with:
$ret->fromJson($json);
I removed that line and I now get JSON. I still wonder why having that object I intitially posted would be helpful and where it could be used. I also wonder why the SDK documentation doesn't explicitly state that the SDK does not return JSON as the final format. I feel it would save a lot of time if PayPal informed a developer that the response gets converted to an object, so we wouldn't have to search through thousands of lines of code to figure it out.
It's likely the SDK is accepting JSON on the communications layer and then running json_decode to pass you back an object you can work with. My own API system converts the response back into a PHP array.
json_decode( $call->execute(array('PayPal\Rest\RestHandler'), "/v1/vault/credit-card/$creditCardId", "GET", $payLoad) );
I'm using the tumblr API and the following code:
$var = xhttp::toQueryArray($response['body']);
print_r($var);
This print on the screen the following:
Array ( [{"meta":{"status":200,"msg":"OK"},"response":{"user":{"name":"lukebream","likes":0,"following":8,"default_post_format":"html","blogs":[{"name":"lukebream","url":"http:\/\/lukebream.tumblr.com\/","followers":5,"primary":true,"title":"Untitled","admin":true,"queue":0,"ask":false,"tweet":"N"}]}}}] => )
How can I access the individual elements and assign them to variables?
Here is what I have finished with:
$tumblr->set_token($_SESSION['oauth_token'], $_SESSION['oauth_token_secret']);
$data = array();
$data['post'] = array();
$response = $tumblr->fetch('http://api.tumblr.com/v2/user/info', $data);
if($response['successful']) {
echo $response['json']['response']['url'];
} else {
echo "api call failed. {$response[body]}<br><br>";
}
It's called JSON, you can parse it using json_decode()
Usage Example :
//I used file_get_contents() to keep things simple
$jsonData = file_get_contents("http://api.tumblr.com/v2/blog/lukebream.tumblr.com/info?api_key=<api_key_here>");
The $jsonData contains :
{
"meta":{
"status":200,
"msg":"OK"
},
"response":{
"blog":{
"title":"Untitled",
"posts":61,
"name":"lukebream",
"url":"http:\/\/lukebream.tumblr.com\/",
"updated":1321830278,
"description":"",
"ask":false,
"likes":0
}
}
}
after it goes through json_decode(), we get a PHP object, so :
$obj = json_decode($jsonData);
will return :
stdClass Object
(
[meta] => stdClass Object
(
[status] => 200
[msg] => OK
)
[response] => stdClass Object
(
[blog] => stdClass Object
(
[title] => Untitled
[posts] => 61
[name] => lukebream
[url] => http://lukebream.tumblr.com/
[updated] => 1321830278
[description] =>
[ask] =>
[likes] => 0
)
)
)
Then you can access the data like with any other object.
You can also use json_decode($str, TRUE): this will return an ARRAY instead of an object, much easier to play with!
I have a WCF Operation GetColors which returns a list of colors as GetColorsResult. I am getting the result fine, but how do I loop through GetColorsResult in php and echo each element?
I am doing:
<?php
header('Content-Type: text/plain');
echo "WCF Test\r\n\r\n";
// Create a new soap client based on the service's metadata (WSDL)
$client = new SoapClient('http://localhost:8181/Colors.svc?wsdl',array(
'login' => "test", 'password' => "test"));
$retval = $client->GetColors();
//Need to loop throuh $retval here
echo $retval->GetColorsResult; //This throws error.
?>
Is there way to control the name of the result, for example, I did not specify WCF to return GetColorsResult, it appended Result to my method call. Likewise, it appends Response to GetColors for the Response (GetColorsResponse)
Output when doing print_r($retval):
stdClass Object
(
[GetColorsResult] => stdClass Object
(
[Color] => Array
(
[0] => stdClass Object
(
[Code] => 1972
[Name] => RED
)
[1] => stdClass Object
(
[Code] => 2003
[Name] => BLUE
)
[2] => stdClass Object
(
[Code] => 2177
[Name] => GREEN
)
)
)
)
regarding to your print_r this should give you all the values:
<?php
$colorResult = $retval->GetColorsResult;
foreach($colorResult->Color as $color){
echo $color->Code . " " . $color->Name . "<br />";
}
?>
is this what you needed?
BR,
TJ
EDIT:
If you just need it for debugging purposes, you should use print_r.
Have a look here: print_r PHP Documentation