Trying to extract value from Soap XML output - php

I'm using PHP SoapClient to call a SOAP service.
I'm using the following code to return the below view
$response = $client->Get($request);
echo '<pre>';
print_r($response);
echo '</pre>';
echo '<hr>';
Here's the response
stdClass Object
(
[TransactionID] => 17ACE7B75CB6SDBX
[ResponseType] => SYNC
[Parameters] => stdClass Object
(
[Param] => stdClass Object
(
[_] => SANDBOX20101001123321125.168.214.72125.168.253.29912003D60E04CC4C1F8
[id] => SessionLogRecord
)
)
)
Here is , showing the elements within it that I want to extract the values of
<onlinesessionrecord><serviceid>SANDBOX</serviceid><datetime>20101001123321</datetime><ipaddress>125.168.214.72</ipaddress><nasipaddress>125.168.253.2</nasipaddress><nasport>9912</nasport><sessionid>003D60E04CC4C1F8</sessionid></onlinesessionrecord>
For example, I am trying to extract from above
I have tried to display it using the following, but I get an error "Attempt to read property "onlinesessionrecord" on string"
$data = $response->Parameters->Param->_->onlinesessionrecord->ipaddress;
print_r($data);
If anyone knows what I'm doing wrong, your advice would be appreciated.
I am sure this is very simple, I just seem to struggle with xml.
--- Next Day, further findings after help from comments ---
So, thanks to the comments below, I have now go to this point. If I use the below:-
$data = simplexml_load_string($response->Parameters->Param->_);
$out = $data->IPAddress; // same if I do the following $data[0]->IPAddress;
print_r($out);
I get this:-
SimpleXMLElement Object ( [0] => 125.168.214.72 ) if I do the below.
But I just want to extract the IPAddress value and assign it to a variable. I have tried 2 ways
$out = $data->IPAddress;
and
$out = $data[0]->IPAddress;
Both give the same output, I just want to actual IPAddress and assign it to a variable.

Related

Trying to get property of non-object in json_decode

i am new to JSON i have a json object retrieved from the database in the form of
Array
(
[0] => stdClass Object
(
[id] => 1
[data] => {"vehicle":[{"year":"2000","make":"Ac","model":"Aceca","acquired_year":"2016","acquired_month":"2","use":"Business","distance_driven_to_work_or_school":"2","distance_driven_manually":"10000"}],"first_name":"ADAS","last_name":"DSADSADA","email":"asddsa#sda.com","phone":"dsasasa","postal_code":"","drivers":[{"name":"ssada","birth_year":"2016","birth_month":"2","birth_day":"2","gender":"female","martial_status":"Single","license_number_provided":"yes","license_number":"asddasdas","license_type":"","training_completed":"","years_been_listed_on_auto_policy_in_north_america":"No Previous Experience","license_suspensions":"","accidents":"Select","convictions":"Select","cancellation_reason":"","cancellation_year":"","cancellation_month":"","cancellation_day":""}],"considering_renters_to_reduce_rate":"yes","install_winter_tires":"no","park_in_private_driveway":"yes","willing_to_install_device":"no","years_insured_with_current_company":"4 Years","how_heard_about_us":"asdaa"}
[date] => 2017-11-20 18:17:52
[status] => 0
)
)
now when i try to use json_decode to convert it into an array i am getting Trying to get property of non-object here's my code
<?php
echo "<pre>";
print_r($quotes); //works fine uptil here
$data = json_decode($quotes->data,true);//the error line
echo "<pre>";
print_r($data);
?>
i tried it a couple of ways but it is not working i tried some other solutions as well stil ending up getting errors any help?
It is because $quotes is an array of objects. Try $quotes[0]->data, e.g.:
$data = json_decode($quotes[0]->data,true);
// ------------------------^^^
You're receiving an array containing objects from the database. You're almost there but instead of
$data = json_decode($quotes->data,true);
You should use
$data = json_decode($quotes[0]->data,true);

Could not convert json string to array using PHP

I need one help. I am unable to convert string to json array using PHP. I am explaining my code below.
$education=$_POST['education'];
the above line give this output [{'name':'aaa','id':'12'},{'name':'bbb','id':'20'}]. But its coming as a string .I tried to convert into array like below but it gived output as null
$edu=json_decode($education,true);
print_r($edu);
It gives the empty output. Here I need to convert it to array and populate all data. Please help me.
Hi You need to make your json string like below:
$arr = '[{"name":"aaa","id":"12"},{"name":"bbb","id":"20"}]';
$a = json_decode($arr);
echo "<pre>";
print_r($a);
die;
it will show your output like below:
Array
(
[0] => stdClass Object
(
[name] => aaa
[id] => 12
)
[1] => stdClass Object
(
[name] => bbb
[id] => 20
)
)
In php, you can use this function to check valid json:
function _isJsonString($string) {
json_decode($string);
return (json_last_error() == JSON_ERROR_NONE);
}
You can also check online for valid json: http://json.parser.online.fr/
Hope this will help.

Parse Json Object PHP

I want to parse the following Json-Object:
{"multicast_id":123456,"success":0,"failure":1,"canonical_ids":0,"results":[{"error":"InvalidRegistration"}]}
I was able to succefully parse the values from success, failure, etc, but am having difficulties getting the "error"-msg ("InvalidRegistration").
I access them like this:
$b = json_decode($a, true);
if($b['success'] == 1){
$result = true;
}
How do i access the results / error section?
I tried to do it like this:
$b['results']['error']
but it didn't work.
Thank you for your help, in advance.
After you use json_decode function, a php array will be produced that will have the following structure:
Array
(
[multicast_id] => 123456
[success] => 0
[failure] => 1
[canonical_ids] => 0
[results] => Array
(
[0] => Array
(
[error] => InvalidRegistration
)
)
)
which means that in order to access the error key inside the results array you need to type $b['results'][0]['error']. Of course, this is not the optimal way unless you know that there is always going to be one index in the results array. In the case where an unknown number of indexes existed ([0], [1], [2] ... [n]), it would be a better idea to create a loop and go through each of them.

How do I retrieve a node from an array using simplexmlelement or other XML function?

I'm using Linkedin API -->
https://developer.linkedin.com/documents/profile-fields#company
Everything is working fine, I can connect to the API with no problem. Bellow follow the data returned by the API when I request some data.
Here is my request (I will not post the whole code, it is more than 500 lines) but it is the essence of what I want to retrieve.
$response2 = $OBJ_linkedin->profile('~:(recommendations-received)');
if($response2['success'] === TRUE)
{
$response2['linkedin'] = new SimpleXMLElement($response2['linkedin']);
echo "<pre>" . print_r($response2['linkedin'], TRUE) . "</pre>";
}
else
{
// request failed
echo "Error: <br />RESPONSE:<br /><br /><pre>" . print_r($response2) . "</pre>";
}
Above follow the response:
SimpleXMLElement Object
(
[recommendations-received] => SimpleXMLElement Object
(
[#attributes] => Array
(
[total] => 1
)
[recommendation] => SimpleXMLElement Object
(
[id] => 0123456
[recommendation-type] => SimpleXMLElement Object
(
[code] => service-provider
)
[recommendation-text] => Here come the recommendation text from the API.
[recommender] => SimpleXMLElement Object
(
[id] => npAnFGrTys
[first-name] => John
[last-name] => Doe
)
)
)
)
Now my question:
How to retrieve and print only the [recommendation-text] node? I'm already calling only the recommendations-received $response2 = $OBJ_linkedin->profile('~:(recommendations-received)'); but it returns the whole thing, then how to get only the [recommendation-text] ???
I have try with simplexmlelement (http://br2.php.net/manual/en/class.simplexmlelement.php), but with no success.
Thanks in advance for any, any help.
[RESULT]
I will post what was the answer that worked out to me.
I'm using the following code as suggested #Mircea:
$sxml = new SimpleXMLElement($response2['linkedin']);
$res = $sxml->xpath('recommendations-received/recommendation/recommendation-text');
echo $res[0];
Instead of this code:
$response2['linkedin'] = new SimpleXMLElement($response2['linkedin']);
echo "<pre>" . print_r($response2['linkedin'], TRUE) . "</pre>";
The difference here is now I'm using the xpath method to search the simpleXML node for children matching. Thanks #Mircea.
You should try xpath function of simplexmlelement http://www.php.net/manual/en/simplexmlelement.xpath.php. I think that the corect way to get what you want is:
$sxml->xpath('recommendations-received/recommendation/recommendation-text')
It returns an array, so you should iterate on it (look at the examples on that page). The xpath query is something like that, it ultimately depends on the structure of the xml received.
Hope it helps.
Accessing the recommendation-text property would be done via something like:
foreach($response2->{recommendations-received} as $recommendation) {
$recommendation->{recommendation-text}
}

capture the value of an element in array returned by simpleXML in PHP?

Any idea how can i get a single value from an element in array returned by an XML which looks like this?
SimpleXMLElement Object
(
[status] => SimpleXMLElement Object
(
[id] => 0
[description] => Success
)
......
I want to capture the [id] and return that value to run tests against it.
the above was captured using the following
$xml = simplexml_load_string($result);
Thanks
Try this $id = $xml->status->id;
Are you looking for something like:
$sxml = new SimpleXMLElement("<statuses><status><id>0</id><description>success</description></status></statuses>");
var_dump((string) $sxml->status[0]->id);

Categories