Get PHP array from XML responce with namespaces - php

I receive an XML repsonce from a GEO service (PDOK). The $responce->raw_body contains this XML structure:
<xls:GeocodeResponse xmlns:xls="http://www.opengis.net/xls" xmlns:gml="http://www.opengis.net/gml">
<xls:GeocodeResponseList numberOfGeocodedAddresses="1">
<xls:GeocodedAddress>
<gml:Point srsName="EPSG:28992">
<gml:pos dimension="2">121299.73296672151 487003.8972524117</gml:pos>
</gml:Point>
<xls:Address countryCode="NL">
<xls:StreetAddress>
<xls:Street>Rokin</xls:Street>
</xls:StreetAddress>
<xls:Place type="MunicipalitySubdivision">Amsterdam</xls:Place>
<xls:Place type="Municipality">Amsterdam</xls:Place>
<xls:Place type="CountrySubdivision">Noord-Holland</xls:Place>
</xls:Address>
</xls:GeocodedAddress>
</xls:GeocodeResponseList>
</xls:GeocodeResponse>
How can I access the elements in here. For example I want an PHP array to access the element 121299.73296672151 487003.8972524117
to grap the coordinates.
And also the other elements. I used SimpleXML parser but I recieve always null.
I think it has someting to do with the namespaces. But I have no clue how to solve this.
The responce is coming from:
$url = "http://geodata.nationaalgeoregister.nl/geocoder/Geocoder?zoekterm=xxxxx%20xx";
$response = \Httpful\Request::get($url)
->expectsXml()
->send();
$xml = new \SimpleXMLElement($response->raw_body);
print_r( $xml);
output:
SimpleXMLElement Object ( )
Any help is appriciated!

After some digging I found a solution for my problem. Its indeed by the namespaces and when using xpath after the namespace registration you can find the elements you need.
$xml = new \SimpleXMLElement($response);
$xml->registerXPathNamespace('xls', 'http://www.opengis.net/xls');
$xml->registerXPathNamespace('gml', 'http://www.opengis.net/gml');
foreach($xml->xpath('//xls:GeocodeResponseList') as $header)
{
$geocoordinates = $header->xpath('//gml:pos');
$street = (string) ($header->xpath('//xls:Street')[0]);
$place = (string) ($header->xpath('//xls:Place')[2]);
}
echo $geocoordinates[0]; // get the coordinates needs to split on space
echo "<br />";
echo $geocoordinates[0]['dimension']; // get the dimension attribute
echo "<br />";
echo $street;
echo "<br />";
echo $place;

Use "->expectsJson()" instead of "->expectsXml()". Then do this:
$array = json_decode($response->raw_body);
or if you use PHP 7.x: https://github.com/eddypouw/geodata-postal-api

Related

How do I extract data from JSON with PHP with many combined data?

I have this string which contains json and I want to display data in php .
I tried
$inf = json_decode($myString, true);
echo $inf-> myInfluencers[0]->entity->id;
but not working.
{ "myInfluencers":[{"entity":{"id":"123286079528097016","payload":{"kloutId":"123286079528097016",
"nick":"mohammed_mrdi","score":{"score":47.25543551618558,"bucket":"40-49"},"scoreDeltas":{"dayChange":-0.2046305761210192,"weekChange":0.3516640938320563,
"monthChange":0.7581201162824698}}}}
,{"entity":{"id":"75716803548010325","payload":{"kloutId":"75716803548010325","nick":"araakgroup","score":{"score":54.9323603520146,"bucket":"50-59"}
,"scoreDeltas":{"dayChange":-0.009862276843456641,"weekChange":0.14323481098688973,"monthChange":8.744154016599673}}}}
,{"entity":{"id":"165788789554303093","payload":{"kloutId":"165788789554303093","nick":"KypreeAF","score":{"score":68.53700119560989,"bucket":"60-69"},
"scoreDeltas":{"dayChange":-0.04333376347085505,"weekChange":0.3100661156757667,"monthChange":1.8907382052882298}}}}
,{"entity":{"id":"168040592724049656","payload":{"kloutId":"168040592724049656","nick":"amribrahim98","score":{"score":47.3655074204191,"bucket":"40-49"}
,"scoreDeltas":{"dayChange":0.007253630369177699,"weekChange":0.361995305845106,"monthChange":-0.12981608352198748}}}}
,{"entity":{"id":"183521696006191168","payload":{"kloutId":"183521696006191168","nick":"ReemAljeally__","score":{"score":52.861448863866684,"bucket":"50-59"}
,"scoreDeltas":{"dayChange":-0.09571927285505666,"weekChange":-0.12303670830488045,"monthChange":1.7138913867458498}}}}] }.
You need to decode it to an object by setting the 2nd parameter as false.
$inf = json_decode($myString, false);
echo $inf->myInfluencers[0]->entity->id;
You have decoded it to an array. Then you need to use this:
$inf = json_decode($myString, true);
echo $inf['myInfluencers'][0]['entity']['id'];
$inf = json_decode($myString, true);
echo $inf['myInfluencers'][0]['entity']['id'];
that is the syntax . thanks guys

How to access specific value in php and json

I'm using a token:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
and here's the json text(not everything);
{
"success":true,
"data":[{
"id":1,
"creator_user_id":{
"id":1682756,
"name":"Kamilah",
"email":"kamilah#fractal.ae",
"has_pic":false,
"pic_hash":null,
"active_flag":true,
"value":1682756},
"title":"FFS Organization deal"
}]
}
I wanted to display "title" and I always get an error
Notice: Undefined index: creator_user_id in
C:\xampp\htdocs\pipedrive\getjson.php on line 8
Here's my code so far:
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo $object['data']['creator_user_id']['title'];
I'm new to json so I'm just practicing and trying to figure out how to echo a specific value in php. Would be appreciated if you can explain exactly how it works when you echo from json to php.
Thank you! :)
First of all you need to debug the array after using json_decode().
<?php
$url = "https://api.pipedrive.com/v1/deals?api_token=3bd884bb0078f836a56f1464097fb71eac9d50ce";
$response = file_get_contents($url);
$object = json_decode($response, true);
echo "<pre>";
print_r($object); // this will print all data into array format.
?>
As per this array, you do not have title index inside the creator_user_id array. title is a separate index.
Also note that, $object['data'] containing two indexes not one. you can get title as:
<?php
foreach ($object['data'] as $key => $value) {
//print_r($value); // this will print the values inside the data array.
echo $value['title']."<br/>"; // this will print all title inside your array.
}
?>
Result:
FFS Organization deal
Google deal

Foreach array loop for JSON

Here is my PHP/JSON code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$decoded= json_decode($json);
$data=$decoded->matches[0];
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
Now I have the following problem
Notice: Trying to get property of non-object
and
Notice: Undefined property: stdClass::$team1
I just want use foreach loop and then show my results in HTML.
Why I am getting the 2 mentioned problems and how can I show the correct results?
Ok so the url your are using return VALID JSON, no need to change any of it!
I suggest using arrays, it has always appeared simpler to me
Do you want the logo_url from team or image_url from league? I will show both in my implementation.
So here is some corrected code
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
//I am not sure which one you want!!!
echo $value['league']['image_url'] . "<br>";
echo $value['team1']['logo_url'] . "<br>";
echo $value['team2']['logo_url'] . "<br>";
}
*EDIT To show wanted implementation by questions author...
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
echo "
<img src=\"http://dailydota2.com/{$value['team1']['logo_url']}\">
<img src=\"http://dailydota2.com/{$value['team2']['logo_url']}\">
";
}
I have checked your code and have some notes and hopefully a solution:
1- You are trying to get non existing key from JSON data, that is the message telling you.
2- I am still not sure what do you get from the JSON API. But regarding to dailydota2 documentation there is nothing called image_url under team1. I guess you are looking for logo_url or something like that.
3- Do not change the format of JSON as you do in your code, therefore delete following line:
$json=str_replace('}, ]',"} ]",$json);
Just leave the main JSON output from API as default.
4- When you try to get specific key from the decoded JSON/Array just use following way:
$data = $decoded->{'matches'};
in stead of
$data=$decoded->matches[0];
Reference: http://php.net/manual/en/function.json-decode.php
5- And finally your foreach loop is working but needs the correct key:
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
When all these step is done, it should works.
Here is your final corrected code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded = json_decode($json);
$data = $decoded->{'matches'};
foreach ($data as $value) {
print_r($value->team1->logo_url);
echo '<img src="http://dailydota2.com/' . $value->team1->logo_url . '">';
}
It returns following output, and I do not get any errors.
/images/logos/teams/cdecgaming.png/images/logos/teams/teamempire.png
/images/logos/teams/ehome.png/images/logos/teams/ehome.png
/images/logos/teams/fnatic.png/images/logos/teams/cloud9.png
/images/logos/teams/teamissecret.png/images/logos/teams/teamissecret.png
/images/logos/teams/natusvincere.png/images/logos/teams/fnatic.png
Again I really do not know which information you want to get from the API but here you have a base of working code that you can work further with to get the required data from the right KEYs.

How to put XML into my SoapClient Call using a Method

I have generated some XML which is saved to a file.
Dummy_Order.xml
In the following code I wanted to open the XML and use it in the method 'ImpOrders'
Here is my code
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$proxy = new SoapClient('http://soapclient/wsdl/Web?wsdl', array ('trace' => 1));
if (file_exists('Dummy_Order.xml')) {
$xml = file_get_contents('Dummy_Order.xml');
} else {
exit('Failed to open XML.');
}
$xmlstring = new SimpleXMLElement($xml);
$result = $proxy->ImportOrders($xmlstring);
var_dump($result);
echo "REQUEST:\n" . $proxy->__getLastRequest() . "\n";
?>
I am getting a response in $result of 0 imported 0 skipped. So i then did getLastRequest() and it's adding the code from the Method but not adding my XML. It wants my XML in a string - which it current is in and isnt moaning about that (It does moan if i use it ->asXML).
I have tried
$result = $proxy->ImportOrders();
and
$result = $proxy->ImportOrders($xmlstring);
And both show the same result in _getLastRequest, which led me to believe that my string isn't being plugged in.
When I check the functions using _getFunctions it provides the information of this...
ImportResult ImportOrders(string $Orders)
Any help would be awesome!
Ok so i resolved it. All i needed to do was wrap my answer in <<
Like below.
$teststring = <<<XML
$xml
XML;
$result = $proxy->ImportOrders($teststring);
Hope this helps out anyone else using PHP, SoapClient and XML.

Extract attribute from simple XML element in PHP

Driving me bonkers- I've got a simple XML element, and I just want to extract the '_Code' attribute. How would I do it?
<?php
$responseCode = "<STATUS _Condition='FAILURE' _Code='0705' _Description='Search failed subject not found' />";
$xml = simplexml_load_string($responseCode);
print_r($xml);
$code = $xml=>#attributes=>_Code; // Parse error
$code = $xml['#attributes']['_Code']; // Returns blank
echo "CODE = ".(string)$code;
?>
CODE =
http://php.net/manual/en/function.simplexml-load-string.php
Use SimpleXMLElement::attributes()
$attrs = $xml->attributes();
$code = $attrs['_Code'];

Categories