Valid XML creation with PHP

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
mavera2
Forum Newbie
Posts: 8
Joined: Sat Sep 03, 2011 11:54 am

Valid XML creation with PHP

Post by mavera2 »

With the following code i can create an xml file.

Code: Select all

<?php
	$myXML = new SimpleXMLElement("<myroot></myroot>");
	$title= $myXML->addChild('title');
	$title->addAttribute('number','12');
	$titleName= $title->addChild('titleName', 'title1');
	$titleLink= $title->addChild('titleLink', 'link1');
	Header('Content-type: text/xml');
	echo $myXML->asXML();
?>
But when i check the validity of xml file
http://www.validome.org/xml/validate/
This error occurs:
Can not find declaration of element 'myroot'.

I suppose that the problem is missing of
!DOCTYPE and
!ELEMENT lines.

How can i create valid XML documents with PHP automatically??
Is it possible to make it without writing doctype and element types
for the whole element types of xml by hand
$title, $titleName and $titleLink

Thank you
User avatar
ok
Forum Contributor
Posts: 393
Joined: Wed May 31, 2006 9:20 am
Location: The Holy Land

Re: Valid XML creation with PHP

Post by ok »

What is the purpose you use this XML for?

The XML validator needs the !DOCTYPE declaration to validate against. The !DOCTYPE refers the validator to a file which has all the declarations of the elements inside your XML file.
If you use this XML internally, you don't need to validate it, since SimpleXML produces a XML document which is well structured.
Post Reply