我想使用CodeIgniter在XML文件中创建一个元素,但每次我都会遇到致命错误:“调用未定义的方法SimpleXMLElement :: createElement()”。这是我在Controller,View&中的代码。模特课,我做错了什么?
控制器(xml_insert.php):
<?php
class Xml_insert extends CI_Controller {
function index() {
$this->load->model('xml_insert_model');
$data['rows'] = $this->xml_insert_model->getAll();
$this->load->view('xml_insert_view', $data);
}
function insert() {
$this->load->model('xml_insert_model');
$data['rows'] = $this->xml_insert_model->getAll();
foreach ($data['rows'] as $r) {
$path1 = $r->xml_file_path;
$xml = simplexml_load_file($path1);
$newAct = $_POST['activity'];
$root = $xml->firstChild;
$newElement = $xml->createElement('activity');
$root->appendChild($newElement);
$newText = $xml->createTextNode($newAct);
$newElement->appendChild($newText);
$xml->save('$path1');
$this->index();
}
}
}
查看(xml_insert_view.php):
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<?php foreach ($rows as $r): ?>
<?php
$path1 = $r->xml_file_path;
$xml = simplexml_load_file($path1);
?>
<?php foreach ($xml->children() as $activity) : ?>
<?php echo "Activity : " . $activity . " <br />"; ?>
<?php endforeach; ?>
<?php endforeach; ?>
<form name="input" action="index.php/xml_insert/insert" method="post">
insert activity:
<input type="text" name="activity"/>
<input type="submit" value="send"/>
</form>
</body>
</html>
型号(xml_insert_model.php):
<?php
class Xml_insert_model extends CI_Model
{
function getAll()
{
$q = $this->db->get("XML");
if ($q->num_rows > 0) {
foreach ($q->result() as $row) {
$data[] = $row;
}
return $data;
}
}
}
XML文件(sample.xml)
<?xml version="1.0"?>
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>Jogging</activity>
<activity>Theatre</activity>
<activity>Programming</activity>
<activity>driving</activity>
<activity>eating</activity>
</list>
答案 0 :(得分:1)
我认为您正在尝试使用DomDocument
而不是
$xml = simplexml_load_file($path1);
尝试
$xml = new DomDocument();
$xml->load($path1);
如果您愿意,可以使用addChild
simpleXML
方法。