简体   繁体   中英

How to use createElement() function in CodeIgniter?

I want to create an element in XML file using CodeIgniter, but every time I'm getting a fatal error: "Call to undefined method SimpleXMLElement::createElement()". Here is my code in Controller, View & Model class, what am I doing wrong?

Controller (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();
    }
}

}

View (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>

Model (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 file(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>

I think you are trying to use functions of DomDocument

instead of

$xml = simplexml_load_file($path1);

Try

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

You can use addChild method of simpleXML if you prefer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM