Extract attribute from simple XML element in PHP - 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'];

Related

Get PHP array from XML responce with namespaces

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

Error while loading xml file?

Am dynamically loading an xml file and sending request to the api but getting
Warning: DOMDocument::loadXML(): Empty string supplied as input in /home/spotrech/public_html/ but this error is very inconsistent sometime appear sometime don't! I really no idea how to solve this. below is code
$rechargeApiUrl = "http://allrechargeapi.com/apirecharge.ashx?uid=$uid&apikey=$apike&number=$mobileNo&opcode=$opId&amount=$amount&ukey=$uniId&format=xml";
$url = file_get_contents($rechargeApiUrl);
$xmlDoc = new DOMDocument();
$xmlDoc->loadXML(preg_replace('/(<\?xml[^?]+?)utf-16/i', '$1utf-8', $url));
$itemInfo = $xmlDoc->getElementsByTagName('Result'); //returns an object.
$itemCount = $itemInfo->length;
foreach ($itemInfo as $userInfo) {
//Assigning node values to its specified variables.
$ukey = strtolower($userInfo->getElementsByTagName('ukey')->item(0)->childNodes->item(0)->nodeValue);
$status = $userInfo->getElementsByTagName('status')->item(0)->childNodes->item(0)->nodeValue;
$resultCode = $userInfo->getElementsByTagName('resultcode')->item(0)->childNodes->item(0)->nodeValue;
}
$strStatus = strtolower(trim($status));
$strResultCode = trim($resultCode);
$strCode = trim($ukey);
any response will be appreciated.Thank you

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.

Extracting data from Wikipedia API

I would like to be able to extract a title and description from Wikipedia using json. So... wikipedia isn't my problem, I'm new to json and would like to know how to use it. Now I know there are hundreds of tutorials, but I've been working for hours and it just doesn't display anything, heres my code:
<?php
$url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$pageid = $data->query->pageids;
echo $data->query->pages->$pageid->title;
?>
Just so it easier to click:
http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids
I know I've probably just done a tiny thing wrong, but its really bugging me, and the code... I'm used to using xml, and I have pretty much just made the switch, so can you explain it a bit for me and for future visitors, because I'm very confused... Anything you need that I haven't said, just comment it, im sure I can get it, and thanks, in advance!
$pageid was returning an array with one element. If you only want to get the fist one, you should do this:
$pageid = $data->query->pageids[0];
You were probably getting this warning:
Array to string conversion
Full code:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->title;
I'd do it like this. It supports there being multiple pages in the same call.
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
[0]=>
string(6) "Google"
}
*/
Try this it will help you 💯%
This code is to extract title and description with the help of Wikipedia api from Wikipedia
<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
echo "<b>Title:</b> ".$title."<br>";
$string=$data->query->pages->$pageid->extract;
// to short the length of the string
$description = mb_strimwidth($string, 0, 322, '...');
// if you don't want to trim the text use this
/*
echo "<b>Description:</b> ".$string;
*/
echo "<b>Description:</b> ".$description;
?>

how to parse xml with php

I am trying to read a weather feed from Yahoo to my site.
Using the code below I was able to print the xml.
What I really want to achieve now is to put the temperature and image in two different variables
$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
print "yahooWeather". $returnYahooWeather;
//$temperature
//$image
You should go ahead and use simplexml or DOM to parse the XML and then you can iterate over the results. With SimpleXML this looks like this:
$zipCode = "44418";
$url = "http://weather.yahooapis.com/forecastrss";
$zip = "?w=$zipCode";
$fullUrl = $url . $zip.'&u=c';
$curlObject = curl_init();
curl_setopt($curlObject,CURLOPT_URL,$fullUrl);
curl_setopt($curlObject,CURLOPT_HEADER,false);
curl_setopt($curlObject,CURLOPT_RETURNTRANSFER,true);
$returnYahooWeather = curl_exec($curlObject);
curl_close($curlObject);
//print "here". $returnYahooWeather;
$xmlobj=simplexml_load_string($returnYahooWeather);
$res = $xmlobj->xpath("//yweather:condition");
$tmp = false;
while(list( , $node) = each($res)) {
$tmp = $node;
}
$attribs = $tmp->attributes();
print "Temperature [".$attribs['temp']."]";
I find it easiest to SimpleXML with PHP.
$xml = simplexml_load_string($returnYahooWeather);
echo $xml->Path->To->Temperature;
It's easy enough, and you can use XPath with SimpleXML :). There are other ways of parsing XML too, as previously mentioned DOMDocument is one of them.

Categories