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);
Related
From cURL I´m getting back an response array where I´d like to test the body against a regex pattern. Here is a sample array:
Array ( [body] => 9068205463|admin [headers] => Array ( [0] => HTTP/1.1 200 OK [1] => Date: Mon, 04 May 2015 16:45:56 GMT [2] => Server: Apache [3] => Vary: Accept-Encoding [4] => Content-Encoding: gzip [5] => Content-Length: 38 [6] => Connection: close [7] => Content-Type: text/html ) [engine] => cURL [cached] => )
Here is what my php if statement looks like:
if (!preg_match("/^[0-9]{10}\|[a-zA-Z]+$/", $result['body'])) {
die ("preg_match failed");
}
Question: Why is Die() fired?
Testing pattern here works like expected.
http://www.phpliveregex.com/p/b2W
Strange as this is working on my localhost but not on a production server.
Php Version is: PHP 5.3.10-1ubuntu3.18 with Suhosin-Patch
You probably have some spaces in your value and that's the reason why it doesn't matches the pattern.
To fix this simply use trim() in preg_match(), e.g.
if (!preg_match("/^[0-9]{10}\|[a-zA-Z]+$/", trim($result['body']))) {
//^^^^^
die ("preg_match failed");
}
I was using the Fulfilled by Amazon (FBA) Inventory API( https://developer.amazonservices.com/doc/fba/inventory/v20101001/php.html/185-9758808-3007701 ) but getting the following error after executing " ListInventorySupplySample.php " . Can anyone please help me know what went wrong.
$request = new FBAInventoryServiceMWS_Model_ListInventorySupplyRequest();
$skus= new FBAInventoryServiceMWS_Model_SellerSkuList();
$skus->setmember(<sku>);
$request->setSellerId(SELLER_ID);
$request->setSellerSkus($skus);
$request->setMarketplace(MARKET_PLACE_ID);
$request->setQueryStartDateTime(date(DATE_FORMAT,strtotime(date("Y-m-d"). ' - 10 days')));
invokeListInventorySupply($service, $request);
Pasting the request.
FBAInventoryServiceMWS_Model_ListInventorySupplyRequest Object
(
_fieldsrotected => Array
(
SellerId => Array
(
FieldValue =>
FieldType => string
)
Marketplace => Array
(
FieldValue =>
FieldType => string
)
SellerSkus => Array
(
FieldValue =>
FieldType => FBAInventoryServiceMWS_Model_SellerSkuList
)
QueryStartDateTime => Array
(
FieldValue => 2014-09-23T00:00:00Z
FieldType => string
)
ResponseGroup => Array
(
FieldValue =>
FieldType => string
)
)
)
Pasting the following response.
HTTP/1.1 401 Unauthorized
Date: Fri, 03 Oct 2014 05:43:55 GMT
Server: AmazonMWS
x-mws-request-id: 0d956be3-5811-40f8-9084-4fbd77a83936
x-mws-timestamp: 2014-10-03T05:43:55.676Z
x-mws-response-context: 6n6IpwjyWO/qMfDqEazU02NkR09zL//rlcQMgApvMkfE7zhCMq2n2OtOE0y0F7AT4rO4RyslSkY=
Content-Type: text/xml
Content-Length: 295
Vary: User-Agent
<?xml version="1.0"?>
<ErrorResponse xmlns="http://mws.amazonaws.com/FulfillmentInventory/2010-10-01/">
<Error>
<Type>Sender</Type>
<Code>AccessDenied</Code>
<Message>Access denied</Message>
</Error>
<RequestID>0d956be3-5811-40f8-9084-4fbd77a83936</RequestID>
</ErrorResponse>
The issue is resolved I was using it in my localhost which is behind a proxy. the moment I uploaded it to the server the things worked. Thanks for your help.
I'm using Abrahams twitter class to search twitter, but can't parse the data. I'm totally stuck, getting different errors whatever i do.
Here's a snippet of the object (?) I am trying to parse:
stdClass Object (
[statuses] => Array (
[0] => stdClass Object (
[metadata] => stdClass Object (
[result_type] => recent
[iso_language_code] => nl
)
[created_at] => Mon Jun 17 16:17:52 +0000 2013
[id] => 346662990684233731
[id_str] => 346662990684233731
[text] => RT #433NL: Als Tahiti vanavond scoort tegen Nigeria volgen we iedereen terug die deze tweet retweet! #confed #433NL
[source] => Twitter for iPhone
[truncated] =>
[in_reply_to_status_id] =>
[in_reply_to_status_id_str] =
What do I need to do in order to parse every piece of data for every tweet? Is there something I have to do with the source data before I can parse it?
Many thanks if you are able to help.
If I can remove the StdClassObject references, I imagine I could parse this easily. How could that be achieved?
Edit: the code is not json, but the original source is a json file.
Looking at Abraham's Twitter class get function's source code, it returns a json_decoded array of PHP objects, as the one you showed us. You could simply do:
$statuses = $connection->get('whatever arguments your using');
if (!empty($statuses)) {
foreach ($statuses as $status) {
echo "{$status->text}\n",
"sent from {$status->source} at {$status->created_at}\n\n";
}
}
For your object the output would be something like:
RT #433NL: Als Tahiti vanavond scoort tegen Nigeria volgen we iedereen terug die deze tweet retweet! #confed #433NL
sent from Twitter for iPhone at Mon Jun 17 16:17:52 +0000 2013
There are some alternative solutions, but this is already simple enough, so I wouldn't bother reinventing the wheel.
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
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)