how to read xml file from url using php

后端 未结 5 1066
广开言路
广开言路 2020-12-03 07:02

I have to read an XML file from an URL

$map_url = \"http://maps.google.com/maps/api/directions/xml?origin=\".$merchant_address_url.\"&destination=\".$cus         


        
5条回答
  •  情深已故
    2020-12-03 07:16

    file_get_contents() usually has permission issues. To avoid them, use:

    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;
    }
    

    Example:

    $xmlstr = get_xml_from_url('http://www.camara.gov.br/SitCamaraWS/Deputados.asmx/ObterDeputados');
    $xmlobj = new SimpleXMLElement($xmlstr);
    $xmlobj = (array)$xmlobj;//optional
    

提交回复
热议问题