I'm trying to an xml response to object via SimpleXMLElement. But an element of XML disappears with this operation. Take a look at XML and SimpleXMLElement clearly:
<item><pubDate>Wed, 28 Dec 2011 13:04:30 GMT</pubDate><title>M 1.2, Nevada</title><description>December 28, 2011 13:04:30 GMT</description><link>http://earthquake.usgs.gov/earthquakes/recenteqsus/Quakes/nn00361989.php</link><geo:lat>37.4048</geo:lat><geo:long>-117.0953</geo:long><dc:subject>1</dc:subject><dc:subject>pasthour</dc:subject><dc:subject>7.00 km</dc:subject><guid isPermaLink="false">nn00361989</guid></item>
And here is the SimpleXMLElement return:
[item] => SimpleXMLElement Object
(
[pubDate] => Wed, 28 Dec 2011 13:04:30 GMT
[title] => M 1.2, Nevada
[description] => December 28, 2011 13:04:30 GMT
[link] => http://earthquake.usgs.gov/earthquakes/recenteqsus/Quakes/nn00361989.php
[guid] => nn00361989
)
As you see there's not geo lat and long info here. I am trying this code for creating SimpleXMLObject:
$doc = new SimpleXMLElement($response)
Must i use an parameter with this?
Your geodata is namespaced in the XML, so you need to tell simplexml that there is also data namespaced with 'geo'
$doc = new SimpleXMLElement($response)
$namespaces = $doc->getNamespaces(true);
$docGeoData = $doc->item->children($namespaces['geo']);
Note that your xml fragment is badly formed because there's no namespace declarations
Perhaps you should try simplexml_load_file
$doc = simplexml_load_file($response)
Related
I'm having troubles to get specific data from a json file using the built-in php functions.
Let me show you some code :
Json File :
{"votes": [ { "date":"November 3rd, 2017 10:08 PM EST", "timestamp":1509743288, "nickname":"Th3ProHack3R", "claimed":"0" }, { "date":"November 3rd, 2017 10:06 PM EST", "timestamp":1509743160, "nickname":"TheKing", "claimed":"0" }, { "date":"November 3rd, 2017 09:45 PM EST", "timestamp":1509741902, "nickname":"some0ne", "claimed":"0" } ] }
My php code :
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes']->nickname;
echo $firstvoter;
I had this code working on a very basic json code without arrays. But something is wrong here because I can't get the nicknames of the voters.
I'm just a little bit confused, so what I wanna do is picking up the nicknames of the voters and then I'll put them on a table using html.
I hope I get a detailed answer so I can understand some of the confusing stuff.
you need to get array to json object. hear "votes" is json object so $data['votes'][0] is return first array see code...
<?php
$json= file_get_contents("myfile.json");
$data = json_decode($json, true);
$voter1 = $data['votes'][0];
$voter2 =$data['votes'][1];
print_r( $voter1);
echo "<br>".$voter1["nickname"];
echo "<br>".$voter2["nickname"];
?>
After converting into json Decode you array make look like this,
Array
(
[votes] => Array
(
[0] => Array
(
[date] => November 3rd, 2017 10:08 PM EST
[timestamp] => 1509743288
[nickname] => Th3ProHack3R
[claimed] => 0
)
[1] => Array
(
[date] => November 3rd, 2017 10:06 PM EST
[timestamp] => 1509743160
[nickname] => TheKing
[claimed] => 0
)
[2] => Array
(
[date] => November 3rd, 2017 09:45 PM EST
[timestamp] => 1509741902
[nickname] => some0ne
[claimed] => 0
)
)
)
In this you need the nickname:
foreach ($jsonData['votes'] as $key => $value) {
echo "Nickname : ". $value['nickname']."<br/>";
}
I have read a standard RSS feed into simpleXML and get the following after converting to an array:
[0] => SimpleXMLElement Object (
[guid] => https://www.zazzle.com/scissors_by_any_other_name_dreadful_pun_t_shirt-235586301981812394
[pubDate] => Wed, 23 Aug 2017 13:41:08 GMT
[title] => SimpleXMLElement Object ( )
[link] => https://www.zazzle.com/scissors_by_any_other_name_dreadful_pun_t_shirt-235586301981812394
[author] => HightonRidley
[description] => SimpleXMLElement Object ( )
[price] => $30.15
)
[1] => SimpleXMLElement Object (
[guid] => {not enough reputation points to show link}
[pubDate] => Sat, 19 Aug 2017 15:53:19 GMT
[title] => SimpleXMLElement Object ( )
[link] => {not enough reputation points to show link}
[author] => HightonRidley
[description] => SimpleXMLElement Object ( )
[price] => $15.65 )
)
This is the code used to create and display the above
$sortable = array();
foreach($product_grid->channel->item as $node) {
$sortable[] = $node;
}
print_r($sortable);
To prove to myself it's working and accessible as intended I used this
foreach ($sortable as $rssitem) {
echo "<br>" . $rssitem->pubDate;
}
echo "<br>".$sortable[0]->pubDate;
echo "<br>".$sortable[1]->pubDate;
and got this output
Wed, 23 Aug 2017 13:41:08 GMT
Sat, 19 Aug 2017 15:53:19 GMT
Wed, 23 Aug 2017 13:41:08 GMT
Sat, 19 Aug 2017 15:53:19 GMT
...but when I try to sort using usort, I get no output and Firefox console tells me I have a server error 500
Here's how I'm using usort
usort($sortable, function($a, $b)
{
return strtotime($a->pubDate) > strtotime($b->pubDate);
});
I've checked various questions/answers on using usort here and as many other places as I can find online but to no avail.
Can someone please tell me how to reference the various elements of $sortable from within that anonymous function. I will be doing other sorts using other elements once I get this first one cracked.
Thanks!
I have an array called $field->selectoptions[1]
print_r($field->selectoptions[1]) gives these results:
stdClass Object ( [voption] => clabels [clabel] => Data Inizio
[values] => Qualsiasi Data 1 Luglio 2016 12 Settembre 2016 14 Novembre
2016 [slabel] => Data Inizio )
I need to remove from [values] all invalid dates, in this case "1 Luglio 2016" (July 1st 2016) because the date has passed
I tried using unset but that's appears to be a single string.
I don't think a str_replace would work either...
Any idea?
I have searched the site and found many resources to help me load and XML file to parse, however after following some of the examples, I can still not get this to work. What am I missing?
thanks
<?php
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$xml = simplexml_load_file($url) or die("feed not loading");
var_dump($xml);
?>
You're most likely confusing what you see in the browser under that URL with an XML document.
What you have at the URL
http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0
is not an XML document. When you request that URL and you look into the response headers, you can see that it is a HTML document:
HTTP/1.1 200 OK
Content-Type: text/html;charset=ISO-8859-1
P3P: CP="IDC CON TEL CUR DEV SAM IND"
Date: Mon, 10 Aug 2015 15:50:46 GMT
Content-Language: en-US
Connection: Keep-Alive
Set-Cookie: X-Mapping-gjinjpae=F462690912B62A0C5476B15FCDB01A81; path=/
Set-Cookie: JSESSIONID=BC6666D2A357FB969A60E05E67B0888C; Path=/
Set-Cookie: JSESSIONID=700D01B2F92909260A05215F86AB8EE5; Path=/
Content-Length: 7147
You can also easily verify that with your browser by making use of the view source feature in your browser or by seeing, that the XML is not displayed "pretty".
However simplexml_load_file expects a well-formed XML document. In your case the main problem you've got is missing error handling. As you interact with a remote system, error handling is crucial for stable use, so make it part of your script:
Dealing with XML errors (SimpleXML - PHP Manual)
Next to that, as it's an HTML document and not an XML document, you need to parse it with a HTML parser - not an XML parser. So don't try with an XML parser at that stage, use a HTML parser first.
How do you parse and process HTML/XML in PHP? (Reference Q&A)
Edit:
The problem with that service is only when you request XML format. If you change the format parameter to JSON (&format=JSON) you can parse the data straight-away despite the wrong response content-type given:
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=JSON&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$result = json_decode(file_get_contents($url));
print_r($result);
Gives:
Array
(
[0] => stdClass Object
(
[response] => stdClass Object
(
[query] => Sales
[location] => 95054
[highlight] => off
[totalresults] => 25406
[start] => 1
[end] => 9
[radius] => 25
[pageNumber] => 0
[results] => Array
(
[0] => stdClass Object
(
[jobtitle] => Sales
[zip] => 95101
[company] => Commercial Janitorial Company
[city] => San Jose
[state] => CA
[country] => US
[date] => 2015-07-14
[url] => http://api.l5srv.net/job_search/api/web/get_job.srv?token=3aeyzv6V2SA%2BKYF5lzqWmxyivVwoE3LFernO291sVVpLbWCG9bBAbVO%2BCGXuN1V%2F9QMmDY3KeK5iYg2phrtjypXtQ82Jngf1q8zQIzix14EuBlSL96sqjffsuHozTZ4SJ6Mf%2B%2BVwRrC65gRtKxH6wg0F50WEZtnD9Xv0%2Bxc2GMhFMszKNEOyrfCNg5YTn%2Flj
[snippet] => Company Description:
We are a Christian owned janitorial company doing business here in the Bay Area for nearly 40 years. You do not have to be Christian to work for us.
We operate in a fast paced, f
[onmousedown] => l5_trk(this)
)
[1] => stdClass Object
(
[jobtitle] => Sales
[...]
The code coming from this server is not valid XML. Try this:
<?php
$url = 'http://api.l5srv.net/job_search/api/web/find_jobs.srv?CID=2239&SID=u9xcvY234AA09&format=XML&q=Sales&l=95054&r=25&s=relevance&a=2014-09-30&start=1&limit=8&highlight=off&userip=25.158.22.121&useragent=Mozilla%2F5.0';
$data = file_get_contents($url);
$data = '<' . '?xml version="1.0" encoding="UTF-8"?' . '>' . str_replace(array("<", ">"), array("<", ">"), $data);
$xml = simplexml_load_string($data) or die("feed not loading");
var_dump($xml);
I don't know how to do this in php. I am trying to get geocode data from openstreetmap.org but I need to do this in php.
In Javascript (and I have this working), it's:
<script type="text/javascript"
src="http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671">
</script>
I have that url but I don't know how to execute it in php.
I have tried:
<?php
$url = "http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671";
$response = file_get_contents($url);
?>
But this doesn't work. I tried the same with curl. Any ideas or is this type of query not possible in php?
Use this;
$xml = simplexml_load_file("http://nominatim.openstreetmap.org/reverse?format=xml&lat=43.642018&lon=-79.374671");
print_r($xml);
which will return you with an array of the values, see below;
SimpleXMLElement Object
(
[#attributes] => Array
(
[timestamp] => Thu, 22 Mar 12 18:31:11 +0000
[attribution] => Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.
[querystring] => format=xml&lat=43.642018&lon=-79.374671
)
[result] => 1, Yonge Street, Corktown, Toronto, Ontario, M5B2H1, Canada
[addressparts] => SimpleXMLElement Object
(
[house_number] => 1
[road] => Yonge Street
[suburb] => Corktown
[city] => Toronto
[county] => Toronto
[state] => Ontario
[postcode] => M5B2H1
[country] => Canada
[country_code] => ca
)
)
Then manipulate the data however you see fit.
It does return
<?xml version="1.0" encoding="UTF-8" ?>
<reversegeocode timestamp='Thu, 22 Mar 12 18:07:13 +0000' attribution='Data Copyright OpenStreetMap Contributors, Some Rights Reserved. CC-BY-SA 2.0.' querystring='format=xml&lat=100&Lon=100'>
<error>Unable to geocode</error></reversegeocode>
That just means that there is no address for that particular coordinate.. This however has
http://nominatim.openstreetmap.org/reverse?format=xml&lat=52.5487429714954&lon=100
Read API if you need more details