问题
I'm triying to parse this address in PHP
$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx' ;
$x1 = simplexml_load_file($url);
But here's what I keep getting
Warning: simplexml_load_file(http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203): failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Server Error in...
As you can see I'm only getting part of the url parameters.
Can you help?
回答1:
With some quick searching on how to retrieve XML via cURL this is what I did to retrieve and parse the XML.
The big reason as I mentioned above in a comment is that you can't pass URLs directly into the simple_xml_load_string function with ampersands(&) in them. It's a character in the XML format that represents entities.
<?php
function get_xml_from_url($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
$xmlstr = curl_exec($ch);
curl_close($ch);
return $xmlstr;
}
$url = 'http://pubapi.yp.com/search-api/search/devapi/search?searchloc=91203&term=pizza&format=xml&sort=distance&radius=5&listingcount=10&key=t266jc29dx';
$contents = get_xml_from_url($url);
$xml = simplexml_load_string($contents);
echo '<pre>';
print_r($xml);
echo '</pre>';
?>
来源:https://stackoverflow.com/questions/44441404/simplexml-load-file-errors