时间:2021-07-01 10:21:17 帮助过:12人阅读
$xml=new SimpleXMLElement(XML数据);
$xml->asXML(文件名);
PHP读取XML文件
XXX= simplexml_load_file(文件名);
1.使用面向对象方式访问XML
classXmlTest
{private$filename = "a.xml";
private$isreading=false;
private$rxml;
//创建XML文件publicfunctionwriteTest()
{$_data = <<
A
B
C
老四
30
Reminder
Don't forget the meeting!
data;$xml = new SimpleXMLElement($_data);
$xml->asXML($this->filename);
}
//读取文件privatefunctionreadFile()
{if(!$this->isreading)
{
$this->rxml= simplexml_load_file($this->filename);
$this->isreading=true;
}
}
//测试:遍历某一数组publicfunctionreaddata()
{$this->readFile();
foreach ($this->rxml->data as$x) {
echo"[".$x."]";
}
echo"
";
}
//测试 用数组下标读取数组某一项publicfunctionreaddata1()
{$this->readFile();
echo"读取第[1]个data数据:";
echo$this->rxml->data[1] ."
";
}
//测试:读取2级XML节点publicfunctionreadfrom()
{$this->readFile();
echo"读取from节点:";
echo$this->rxml->from->name .',';
echo$this->rxml->from->arg."
";
//读取name节点的fristname属性echo$this->rxml->from->name['fristname']."
";
}
}
$tmp = new XmlTest();
$tmp->writeTest();
$tmp->readdata();
$tmp->readdata1();
$tmp->readfrom();
?>
浏览器打印:
[A][B][C]
读取第[1]个data数据:B
读取from数据:老四,30
陈
2.使用xpath访问XML., 用路径获取节点,区别:获取的节点都以数组返回,因此用数组下标访问
publicfunctionreaddata_xpath() {$this->readFile();
$data= $this->rxml->xpath('/root/data');
foreach ($dataas$x) {
echo"[".$x."]";
}
echo"
";
}
publicfunctionreaddata1_xpath()
{$this->readFile();
$data1 = $this->rxml->xpath('/root/data');
echo"读取第[1]个data数据:";
echo$data1[1] ."
";
}
publicfunctionreadfrom_xpath()
{$this->readFile();
$name= $this->rxml->xpath('/root/from/name');
$arg= $this->rxml->xpath('/root/from/arg');
echo"读取from数据:";
echo$name[0] .',';
echo$arg[0]."
";
//读取name节点的fristname属性echo$name[0]['fristname']."
";
}
$tmp->readdata_xpath();
$tmp->readdata1_xpath();
$tmp->readfrom_xpath();
******************
浏览器打印:
[A][B][C]
读取第[1]个data数据:B
读取from数据:老四,30
陈
').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('').text(i));
};
$numbering.fadeIn(1700);
});
});
以上就介绍了 PHP SimpleXMLElement:XML文件解析和读写,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。