本文实例讲述了php的xml文件解释类及其用法,是非常实用的技巧。分享给大家供大家参考。具体如下:
xmlparser.class.php类文件如下:
<?php
/** xml 文件分析类
* date: 2013-02-01
* author: fdipzone
* ver: 1.0
*
* func:
* loadxmlfile($xmlfile) 读入xml文件输出array
* loadxmlstring($xmlstring) 读入xmlstring 输出array
*/
class xmlparser{
/** 读取xml文件
* @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);
}
/** 读取xmlstring
* @param string $xmlstring
* @return array
*/
public function loadxmlstring($xmlstring){
// parser xml
list($flag, $data) = $this->parser($xmlstring);
return $this->response($flag, $data);
}
/** 解释xml内容
* @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);
}
/** 检查xml格式是否正确
* @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;
}
}
/** object 转 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;
}
}
}
}
/** 输出返回
* @param boolean $flag true:false
* @param array $data 转换后的数据
* @return array
*/
private function response($flag=false, $data=array()){
return array($flag, $data);
}
}
?>
demo示例程序如下:
<?php
require "xmlparser.class.php";
$xmlfile = 'file.xml';
$xmlstring = '<?xml version="1.0" encoding="utf-8"?>
<xmlroot>
<status>1000</status>
<info></info>
<result><id>100</id>
<name>fdipzone</name>
<gender>1</gender>
<age>28</age>
</result>
</xmlroot>';
echo '<pre>';
$xml_parser = new xmlparser();
echo "response xmlfilern";
list($flag, $xmldata) = $xml_parser->loadxmlfile($xmlfile);
if($flag){
print_r($xmldata);
}
echo "response xmlstringrn";
list($flag, $xmldata) = $xml_parser->loadxmlstring($xmlstring);
if($flag){
print_r($xmldata);
}
echo '</pre>';
?>
关于php的xml预定义常量可参考官方文档:
http://www.php.net/manual/en/libxml.constants.php
希望本文所述对大家php程序设计的学习有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!