Example code for reading xml data using PHP regular expressions
- Zhang Ying
- Male
- 28
- Tank
- Male
- 28
2. php file processing, rexml. php
- /***
- @ Read xml files using regular expressions
- @ Recoded By Androidyue
- @ Site bbs.it-home.org
- ***/
- $ Xml = "";
- // Open the read object in read-only mode
- $ F = fopen ('person. XML', 'r ');
- // Format and obtain the read data
- While ($ data = fread ($ f, 4096 )){
- $ Xml. = $ data;
- }
- // Close an opened file pointer
- Fclose ($ f );
- // Read data above
- Preg_match_all ("// (.*?) / /S ", $ xml, $ humans); // match the content in the outermost tag
- // Format the data
- Foreach ($ humans [1] as $ k => $ human ){
- Preg_match_all ("// (.*?) / /", $ Human, $ name); // match the name
- Preg_match_all ("// (.*?) / /", $ Human, $ sex); // match the gender
- Preg_match_all ("// (.*?) / /", $ Human, $ old); // match the age
- }
- // Process result data
- Foreach ($ name [1] as $ key => $ val ){
- Echo $ val. "-". $ sex [$ key] [1]. "-". $ old [$ key] [1]."
";
- }
- ?>
Note: the encoding formats of the two files must be consistent. it is best to set them to the UTF8 character set to avoid inexplicable errors. |