Genalb Bajrami
Genalb Bajrami

Reputation: 41

Fatal error: Uncaught DOMException: Invalid Character Error

I have this problem, about an invalid Character Error and i am not understanding this kind of error. I have a form and through it I am going to insert some information on the xml document called "phonebook.xml".

<?php


if(isset($_POST['submit'])){

    $fn=$_POST['f1'];
    $lm=$_POST['l1'];
    $nt=$_POST['nr'];



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

$rootTag=$xml->getElementsByTagname("root")->item(0);
$infoTag=$xml->createElement("Personal Information");
$fnameTag=$xml->createElement("First Name",$fn);
$lnameTag=$xml->createElement("Last Name",$lm);
$ntTag=$xml->createElement("Number Type",$nt);


$infoTag->appendChild($fnameTag);
$infoTag->appendChild($lnameTag);
$infoTag->appendChild($ntTag);

$rootTag->appendChild($infoTag);
$xml->save("phonebook.xml");



}

?>

Upvotes: 1

Views: 7126

Answers (2)

ThW
ThW

Reputation: 19492

Element names are not allowed to have spaces in them, so Personal Information is an invalid tag name. You can replace/remove the space.

Additionally, the second argument of DOMDocument::createElement() has an broken escaping. The easiest way is to create and append the content as text nodes.

$document = new DOMDocument("1.0","UTF-8");
$document->appendChild($document->createElement('root'));

$rootTag = $document->documentElement;
$infoTag = $rootTag->appendChild(
  $document->createElement("PersonalInformation")
);
$infoTag 
  ->appendChild($document->createElement("FirstName"))
  ->appendChild($document->createTextNode("John"));

$document->formatOutput = TRUE;
echo $document->saveXML();

Output:

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <PersonalInformation>
    <FirstName>John</FirstName>
  </PersonalInformation>
</root>

Upvotes: 3

Genalb Bajrami
Genalb Bajrami

Reputation: 41

The problem is that i shouldn't have space between Personal Information , but should be :PersonalInformation.

Upvotes: 0

Related Questions