Php xml file parsing class (with demo code)
/** XML file analysis class
- * Date: 2013-02-01
- * Author: fdipzone
- * Ver: 1.0
- * Edition bbs.it-home.org
- * Func:
- * LoadXmlFile ($ xmlfile) reads the xml file and outputs the Array
- * LoadXmlString ($ xmlstring) reads the xmlstring output Array
- */
-
- Class XMLParser {
- /** Read xml files
- * @ Param String $ xmlfile
- * @ Return Array
- */
- Public function loadXmlFile ($ xmlfile ){
- // Get xmlfile content
- $ Xmlstring = file_exists ($ xmlfile )? File_get_contents ($ xmlfile ):'';
-
- // Parser xml
- List ($ flag, $ data) = $ this-> parser ($ xmlstring );
- Return $ this-> response ($ flag, $ data );
- }
-
-
- /** Read xmlstring
- * @ Param String $ xmlstring
- * @ Return Array
- */
- Public function loadXmlString ($ xmlstring ){
- // Parser xml
- List ($ flag, $ data) = $ this-> parser ($ xmlstring );
-
- Return $ this-> response ($ flag, $ data );
- }
-
- /** Interpret xml content
- * @ Param String $ xmlstring
- * @ Return Array
- */
- Private function parser ($ xmlstring ){
- $ Flag = false;
- $ Data = array ();
-
- // Check xml format
- If ($ this-> checkXmlFormat ($ xmlstring )){
- $ Flag = true;
-
- // Xml to object
- $ Data = simpleXML_load_string ($ xmlstring, 'simplexmlelement', LIBXML_NOCDATA );
-
- // Object to array
- $ This-> objectToArray ($ data );
- }
- Return array ($ flag, $ data );
- }
-
- /** Check whether the xml format is correct
- * @ Param String $ xmlstring
- * @ Return boolean
- */
- Private function checkXmlFormat ($ xmlstring ){
- If ($ xmlstring = ''){
- Return false;
- }
-
- $ Xml_parser_obj = xml_parser_create ();
-
- If (xml_parse_into_struct ($ xml_parser_obj, $ xmlstring, $ vals, $ indexs) === 1) {// 1: success 0: fail
- Return true;
- } Else {
- Return false;
- }
- }
/** Convert object to Array
- * @ Param object $ object
- * @ Return Array
- */
- Private function objectToArray (& $ object ){
- $ Object = (array) $ object;
- Foreach ($ object as $ key => $ value ){
- If ($ value = ''){
- $ Object [$ key] = "";
- } Else {
- If (is_object ($ value) | is_array ($ value )){
- $ This-> objectToArray ($ value );
- $ Object [$ key] = $ value;
- }
- }
- }
- }
/** Output return
- * @ Param boolean $ flag true: false
- * @ Param Array $ data converted data
- * @ Return Array
- */
- Private function response ($ flag = false, $ data = array ()){
- Return array ($ flag, $ data );
- }
- }
- ?>
2. Demo
- Require "XMLParser. class. php ";
-
- $ Xmlfile = 'File. XML ';
- $ Xmlstring ='
-
- 1000
-
- 100
- Fdipzone
- 1
- 28
-
- ';
-
- Echo'
'; -
- $xml_parser = new XMLParser();
- echo "response xmlfile\r\n";
- list($flag, $xmldata) = $xml_parser->loadXmlFile($xmlfile);
- if($flag){
- print_r($xmldata);
- }
-
- echo "response xmlstring\r\n";
- list($flag, $xmldata) = $xml_parser->loadXmlString($xmlstring);
- if($flag){
- print_r($xmldata);
- }
-
- echo '
';
- ?>
Php xml predefined constant: http://bbs.it-home.org/shouce/php5/libxml.constants.html |