doufang8965 2015-11-04 20:38
浏览 97
已采纳

使用simplexml_load_file在&中发出&的问题

simplexml_load_file() does not load XML file when the URL includes an ampersand symbol. I have tried two examples with and without ampersand:

$source1 = simplexml_load_file("http://www.isws.illinois.edu/warm/data/outgoing/nbska/datastream.aspx?id=ncu");
print_r($source1); //works

$source2 = simplexml_load_file("http://forecast.weather.gov/MapClick.php?lat=38.8893&lon=-77.0494&unit=0&lg=english&FcstType=dwml");    
print_r($source2); //no output

First example works well as it does not includes ampersand, but the second example does not work as it include ampersand.

I have referenced simplexml_load_file with & (ampersand) in url with Solr and simplexml_load_file ampersand in url but it did not work.

  • 写回答

1条回答 默认 最新

  • douzhan1868 2015-11-04 20:51
    关注

    The issue is not the ampersand in the URL. The issue, instead, is that weather.gov appears to be blocking these types of requests. They will not allow users that do not have a useragent set.

    The fastest way to get around this is to set a UserAgent within PHP, which you can do by putting this code above your xml call:

    ini_set('user_agent', 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0) Gecko/20100101 Firefox/9.0');
    

    However, I would recommend using CURL instead of simplexml_load_file, as simplexml_load_file is often restricted by server configuration. If you were to do this with curl, you'd want to do something like the first answer here: SimpleXML user agent

    I have tested this locally and got it working just by specifying a user agent.

    EDIT: Also, welcome to SO! Be sure to vote often ;D

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?