simplexml

Posted on Posted in php
Tips: 本文创建于2014年5月8日,已超过 2 年,内容或图片可能已经失效!

simpleXML

这是个类,其他代码参考xml增删改查

[code lang="php"]
<?php
header ( 'Content-Type:text/html; charset=utf-8' );
class studentModel {
/**
* 获取xml中的每一个元素值
*/
public function getList() {
$students = array ();
$simpleXML = simplexml_load_file ( './students.xml' );
// 直接遍历xml文件的跟元素下的子元素
foreach ( $simpleXML as $studentElement ) {
// 获取属性
$sn = $studentElement ['sn'];
$id = $studentElement ['id'];
// 获取子节点
$name = $studentElement->name;
$age = $studentElement->age;
$sex = $studentElement->sex;

$student = new stdClass ();
$student->sn = $sn;
$student->id = $id;
$student->name = $name;
$student->age = $age;
$student->sex = $sex;

$students [] = $student;
}

return $students;
}
/**
* 接受ID,删除元素
*/
public function remove($id) {
$root = simplexml_load_file ( './students.xml' );
// 查找要删除的子节点
$studentLength = $root->count (); // 获取子节点的书目
for($i = 0; $i < $studentLength; $i ++) {
// 获取每个子节点上面的ID属性
if ($root->student [$i] ['id'] == $id) {
unset ( $root->student [$i] );
break;
}
}
$root->saveXML ( './students.xml' );
}
/**
* 添加数据
*/
public function add($student) {
$root = simplexml_load_file ( './students.xml' );
// 向根元素下面添加一个student子元素
$studentElement = $root->addChild ( 'student' );
// 添加属性
$studentElement->addAttribute ( 'sn', $student->sn );
$studentElement->addAttribute ( 'id', uniqid () );
// 添加子节点
$studentElement->addChild ( 'name', $student->name );
$studentElement->addChild ( 'age', $student->age );
$studentElement->addChild ( 'sex', $student->sex );
// 保存到文件
$root->saveXML ( './students.xml' );
}
/**
* 根据id的值找到内容
*/
public function get($id) {
$root = simplexml_load_file ( './students.xml' );
foreach ( $root as $studentElement ) {
if ($studentElement ['id'] == $id) {
// 获取属性
$sn = $studentElement ['sn'];
$id = $studentElement ['id'];
// 获取子节点
$name = $studentElement->name;
$age = $studentElement->age;
$sex = $studentElement->sex;

$student = new stdClass ();
$student->sn = $sn;
$student->id = $id;
$student->name = $name;
$student->age = $age;
$student->sex = $sex;

return $student;
}
}
}
/**
* 更新数据
*/
public function update($student) {
$root = simplexml_load_file ( './students.xml' );
foreach ( $root as $studentElement ) {
// id对应的节点
if ($studentElement ['id'] == $student->id) {
$studentElement ['sn'] = $student->sn;
$studentElement->name = $student->name;
$studentElement->age = $student->age;
$studentElement->sex = $student->sex;
break;
}
}
$root->saveXML ( './students.xml' );
}
}

[/code]

» 转载请注明来源:呢喃 » simplexml