Discuss the detailed usage of PHP simplexml

Source: Internet
Author: User

What we want to discuss with you today is about

Xml has become the trend of data storage and transmission. From the popular Ajax last year, it has a method (ResponseXML) to return Xml objects, then Javascript is used to process the Xml object.

Obviously, PHP, the powerful programming language on the server, needs more support from this technology. Compared with popular ones, Xml Parse, XmlReader, Xml Rpc... This is not the case here, but a PHP simplexml already integrated. It is easy to use and does not need to load other files or related configurations. Of course, this is what I use most. I know more about it than other php xml parsing classes.

Suppose we have a file like this,

The XML code for php xml processing is as follows:
 

 
  1. <? Xml version = "1.0" encoding = "UTF-8"?>
  2. <Phplamp>
  3. <Post>
  4. <Title id = "1"> php xml processing Overview 1 </title>
  5. <Details> details 1 </details>
  6. </Post>
  7. <Post>
  8. <Title id = "2"> php xml processing Introduction 2 </title>
  9. <Details> details 2 </details>
  10. </Post>
  11. <Post>
  12. <Title id = "3"> php xml processing Introduction 3 </title>
  13. <Details> details 3 </details>
  14. </Post>
  15. </Phplamp>

Now we need to use the PHP simplexml method to parse all its data.

Php xml processing PHP code is as follows
 

 
  1. <? Php
  2. /**
  3. * Load Xml files
  4. */
  5. $ Xml = simplexml_load_file ("me. xml ");
  6. /**
  7. * If Xml is a string, you can use the following
    Method.
  8. * $ Xml = simplexml_load_string
  9. */
  10. /**
  11. * Traverse $ xml objects
  12. */
  13. Foreach ($ xml as $ key => $ value ){
  14. // Get attributes
  15. $ Attr = $ value-> title-> attributes ();
  16. Echo "Id:". $ attr ['id']. "<br/> ";
  17. Echo "Title:". $ value-> title. "<br/> ";
  18. Echo "Details:". $ value-> details
    . "<Br/> ";
  19. }
  20. ?>

The preceding section describes how to use PHP simplexml.


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.