简体   繁体   中英

How to insert current date in XML - PHP?

I'm trying to insert current date in every record of my XML without typing the date just taking it from function and insert in the record but without success.

My task is to make form - book with 'author' and 'title' and if you write the existing author with the title in XML - to change only the date of the current record фтв not to make the new record.

But first I need to get this current date somehow. So I tried this way:

if(isset($_GET['insert']))
{

  $xml = new DomDocument("1.0","UTF-8");
  $xml -> load('book.xml');

  $date = date('Y m d'); //  get date


  $b_author = $_GET['author'];
  $b_title=$_GET['title'];


  $rootTag = $xml->getElementsByTagname('root')->item(0);

  $bookTag = $xml->createElement("book"); 
  $authorTag = $xml->createElement("author",$b_author);
  $titleTag = $xml->createElement("title",$b_title);

  $dateTag = $xml->createElement($date); // create element date


  $bookTag->appendChild($authorTag);
  $bookTag->appendChild($titleTag);
  $bookTag->appendChild($dateTag); // append date

  $rootTag->appendChild($bookTag);
  $xml->save('book.xml');

}

So in browser I have this error :

> Fatal error: Uncaught DOMException: Invalid Character Error in
> C:\xampp\htdocs\project\Parse XML\insert_inXML.php:26 Stack trace: #0
> C:\xampp\htdocs\project\Parse XML\insert_inXML.php(26):
> DOMDocument->createElement('2018 04 06') #1 {main} thrown in
> C:\xampp\htdocs\project\Parse XML\insert_inXML.php on line 26

You try to add an element like

<2018 04 06></2018 04 06>

The whitespaces are the problem.

I guess you want to have something like

<date>2018 04 06</date>

To get there use DomDocument::createElement() like you did above:

$dateTag = $xml->createElement('date', $date);

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