2014-02-19 50 views
0

我想使用CodeIgniter在XML文件中創建一個元素,但是每次遇到致命錯誤時:「調用未定義的方法SimpleXMLElement :: createElement()」。這是我在Controller中的代碼,查看&模型類,我做錯了什麼?如何在CodeIgniter中使用createElement()函數?

控制器(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中)

​​
+0

你會想要進一步定義你的具體問題。粘貼所有的代碼不會得到你的支持。我的第一個想法是,基於介紹而不需要看代碼,你確定函數createElement是否可用? – bland

回答

1

我認爲你要使用的DomDocument

功能,而不是

$xml = simplexml_load_file($path1);

嘗試

$xml = new DomDocument(); 
$xml->load($path1); 

如果您願意,可以使用addChild方法simpleXML

相關問題