PHP: SimpleXML

2013 年 2 月 19 日4040

Here is a very robust SimpleXML parser. Can be used to load files, strings, or DOM into SimpleXML, or can be used to perform the reverse when handed SimpleXML.

<?php

/**

* XMLParser Class File

*

* This class loads an XML document into a SimpleXMLElement that can

* be processed by the calling application. This accepts xml strings,

* files, and DOM objects. It can also perform the reverse, converting

* an SimpleXMLElement back into a string, file, or DOM object.

*/

class XMLParser {

/**

* While parsing, parse the supplied XML document.

*

* Sets up a SimpleXMLElement object based on success of parsing

* the XML document file.

*

* @param string $doc the xml document location path

* @return object

*/

) {

if ()) {

return );

} else {

throw new .

);

}

}

/**

* While parsing, parse the supplied XML string.

*

* Sets up a SimpleXMLElement object based on success of parsing

* the XML string.

*

* @param string $string the xml document string

* @return object

*/

) {

if (isset($string)) {

return );

} else {

throw new .

);

}

}

/**

* While parsing, parse the supplied XML DOM node.

*

* Sets up a SimpleXMLElement object based on success of parsing

* the XML DOM node.

*

* @param object $dom the xml DOM node

* @return object

*/

) {

if (isset($dom)) {

return );

} else {

throw new .

);

}

}

/**

* While parsing, parse the SimpleXMLElement.

*

* Sets up a XML file, string, or DOM object based on success of

* parsing the XML DOM node.

*

* @param object $path the xml document location path

* @param string $type the return type (string, file, dom)

* @param object $simplexml the simple xml element

* @return mixed

*/

) {

if (isset()) {

switch ($type) {

case 'string':

return ();

break;

case 'file':

if (isset($path)) {

return );

} else {

throw new .

);

}

break;

case 'dom':

return );

break;

}

} else {

throw new .

);

}

}

}

?>

0 0