PHP读取XML文件的方法实例总结【DOMDocument及simplexml方法】

本文实例讲述了PHP读取XML文件的方法,分享给大家供大家参考,具体如下:

使用DOMDocument对象读取xml

创建一个DOMDocument对象

$doc = new DOMDocument();

载入xml文件

$doc->load("book.xml");

获取标签对象

$books = $doc->getElementsByTagName("book");

获取标签的子对象

$titles = $book->getElementsByTagName("title");

获取标签的值或属性

$title = $titles->item(0)->nodeValue;

实例1,获取图书列表

book.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <bookstore>
  3. <book>
  4. <title>PHP和MySQL开发</title>
  5. <author>谭浩强</author>
  6. </book>
  7. <book>
  8. <titile>xml从入门到精通</titile>
  9. <author>郑智化</author>
  10. </book>
  11. </bookstore>

load.php

  1. <?php
  2. header("Content-type:text/html;charset=utf8");
  3. $doc = new DOMDocument(); //创建DOMDocument对象
  4. $doc->load("book.xml"); //打开book.xml
  5. $books = $doc->getElementsByTagName("book"); //获取book标签对象
  6. foreach ($books as $book){ //遍历对象
  7. $titles = $book->getElementsByTagName("title"); //获取book标签下的title标签
  8. $title = $titles->item(0)->nodeValue; //获取标签的值
  9. $authors = $book->getElementsByTagName("author");//获取book标签下的author标签
  10. $author = $authors->item(0)->nodeValue; //获取标签的值
  11. $item["title"] = $title;
  12. $item["author"] = $author;
  13. $bookinfo[] = $item;
  14. }
  15. var_dump($bookinfo);

实例2,读取配置文件

config.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <mysql>
  3. <host>127.0.0.1</host>
  4. <username>root</username>
  5. <password></password>
  6. <database>test</database>
  7. </mysql>

config.php

  1. <?php
  2. header("Content-type:text/html;charset=utf8");
  3. $doc = new DOMDocument(); //创建DOMDocument对象
  4. $doc->load("config.xml"); //打开config.xml
  5. $mysql = $doc->getElementsByTagName("mysql"); //获取mysql标签对象
  6. $host = $mysql->item(0)->getElementsByTagName("host");
  7. $config["host"] = $host->item(0)->nodeValue;
  8. $username = $mysql->item(0)->getElementsByTagName("username");
  9. $config["username"] = $username->item(0)->nodeValue;
  10. $password = $mysql->item(0)->getElementsByTagName("password");
  11. $config["password"] = $password->item(0)->nodeValue;
  12. $database = $mysql->item(0)->getElementsByTagName("database");
  13. $config["database"] = $database->item(0)->nodeValue;
  14. var_dump($config);

使用simplexml方法读取xml

实例1,获取图书列表

load.php

  1. <?php
  2. header("Content-type:text/html;charset=utf8");
  3. $books = simplexml_load_file("book.xml");
  4. foreach($books as $book){
  5. $item["title"] = $book->title;
  6. $item["author"] = $book->author;
  7. $booklist[] = $item;
  8. }
  9. var_dump($booklist);

实例2,读取配置文件

config.php

  1. <?php
  2. header("Content-type:text/html;charset=utf8");
  3. $mysql = simplexml_load_file("config.xml");
  4. $config['host'] = $mysql->host;
  5. $config['username'] = $mysql->username;
  6. $config['password'] = $mysql->password;
  7. $config['databse'] = $mysql->database;
  8. var_dump($config);