PHP读取XML文件的三种方式

2018-08-02 01:59:25   PHP

  php  

一 用 simplexml_load_file 读取xml文件

  1. <?php
  2. $xml_array=simplexml_load_file('person.xml'); //将XML中的数据,读取到数组对象中
  3. foreach($xml_array as $tmp)
  4. {
  5. echo $tmp->name."-".$tmp->sex."-".$tmp->old."<br>";
  6. }
  7. ?>

二 DOMDocument读取xml

  1. <?php
  2. $doc = new DOMDocument();
  3. $doc->load('xml.xml'); //读取xml文件
  4. $humans = $doc->getElementsByTagName( "humans" ); //取得humans标签的对象数组
  5. foreach( $humans as $human )
  6. {
  7. $names = $human->getElementsByTagName( "name" ); //取得name的标签的对象数组
  8. $name = $names->item(0)->nodeValue; //取得node中的值,如<name> </name>
  9. $sexs = $human->getElementsByTagName( "sex" );
  10. $sex = $sexs->item(0)->nodeValue;
  11. $olds = $human->getElementsByTagName( "old" );
  12. $old = $olds->item(0)->nodeValue;
  13. echo "$name - $sex - $old\n";
  14. }

三 利用正则来获取数据

  1. <?php
  2. header("content-type:text/html;charset=utf-8");
  3. $xml = '';
  4. $f = fopen("xml.xml", "r");
  5. while($data = fread($f, 2096))
  6. {
  7. $xml .= $data;
  8. }
  9. fclose($f);
  10. preg_match_all('/\<humans\>(.*?)\<\/humans\>/s', $xml, $humans);
  11. foreach($humans[1] as $human)
  12. {
  13. preg_match_all('/\<name\>(.*?)\<\/name\>/s', $human, $names);
  14. preg_match_all('/\<sex\>(.*?)\<\/sex\>/s', $human, $sexes);
  15. preg_match_all('/\<old\>(.*?)\<\/old\>/s', $human, $olds);
  16. }
  17. foreach($names[1] as $k=>$name)
  18. {
  19. echo $names[1][$k].'-'.$sexes[1][$k].'-'.$olds[1][$k]."\n";
  20. }