Parse XML data in PHP

Source: Internet
Author: User

If you plan to process XML data in PHP, you need an XML library to extract data for you. For example, parse RSS feed or pattern match (search for XHTML images or elements ).

SimpleXML extension provides a very intuitive API to easily convert XML into objects and traverse elements. The only drawback is to load the entire document or a very large XML file in the memory. Its performance may be a problem.

If performance is a factor, you can use XMLReader. XMLReader is an XML parser that traverses each node during the loading process, instead of loading the entire document in the memory.

The following code uses simple XML to obtain the latest RSS from my website. On my server, I have used the Curl library to process HTTP connections because it supports server hosting and is more secure.
 

 
 
  1. <?php 
  2.    
  3. function load_file($url) {  
  4. $ch = curl_init($url);  
  5. #Return http response in string  
  6. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
  7. $xml = simplexml_load_string(curl_exec($ch));  
  8. return $xml;  
  9. }  
  10.    
  11. $feedurl = 'http://naveenbalani.com/index.php/feed/';  
  12. $rss = load_file($feedurl);  
  13.    
  14. foreach ($rss->channel->item as $item) {  
  15. echo "
  16. echo "<p>" . $item->description . "</p>";  
  17. }  
  18.    
  19. ?> 

Http://css.dzone.com/news/parsing-xml-data-php


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.