开发者

Get XML from https URL

I'm trying to get data from multiple XML feeds and copy that data to my local database. I've tried looking into SimpleXML and some other things I've found on the internet but I'm wondering what the best route to take with someth开发者_高级运维ing like this.

I'm looking for something that will not only get the XML from the secure location but also convert it to a series of arrays.


This is a pretty simple process that you can accomplish with CURL and some sort XML to array class. I'll give you details on both here.

The PHP:

/* run mozilla agent */
$agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1';

$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $agent); //make it act decent
curl_setopt($ch, CURLOPT_URL, $url);         //set the $url to where your request goes
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //set this flag for results to the variable
curl_setopt($ch, CURLOPT_POST, 1);           //if you're making a post, put the data here
curl_setopt($ch, CURLOPT_POSTFIELDS, $post); //as a key/value pair in $post
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); //This is required for HTTPS certs if
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //you don't have some key/password action

/* execute the request */
$result = curl_exec($ch);
curl_close($ch);

/* now parse the resulting XML using XMLToArray class from 
Razzaque Rupom http://groups.yahoo.com/group/phpresource/ */
require_once('lib/class.XmlToArray.php');
$parser = new XmlToArray($result);
$data = $parser->createArray();

And there you have it.

  • Mitch


When using SimpleXML you get the XML as an object that contains arrays of your nodes. I personally prefer to use SimpleXML over any other XML-parser, because of the simplicity and overall performance. It's easy to use as a DOM-manipulator when manipulating data as well as easy to retrieve only a few nodes when used as XPath-parser.

If your traversing through a very large XML-file you may be better of with a straight up SAX-parser that loads lazy, but since you're reading over a network I believe the performance differences are negligable.


Use cURL (http://php.net/manual/en/ref.curl.php) to fetch the data from the https location, then simplexml_load_string to load it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜