how to create a valid xml file with php and mysql

K

Kentor

I have some info that im grabbing from a mysql database with php and i
want to make an xml file but i know that i need to be carefull with the
& sign and so on... how can i clean the data coming from the db to have
a valid xml file?
 
M

Martin Honnen

Kentor said:
I have some info that im grabbing from a mysql database with php and i
want to make an xml file but i know that i need to be carefull with the
& sign and so on... how can i clean the data coming from the db to have
a valid xml file?

The latest 5.1.something PHP release has XmlWriter to generate XML:
<www.php.net/XMLWriter>
 
T

Tuomas Rannikko

Kentor said:
anything else =/

I think you should go with the XMLWriter

However

I guess, if you're just putting some character data in semi-fixed tags
(rather than trying to generate the document structure from the db) you
could maybe escape the character data with something like this:


$original = "this&that ]]><foo";
$pattern = array("&", "<", "]]>");
$replacement = array("&amp;", "&lt;", "]]&gt;");
$escaped = preg_replace($pattern, $replacement, $original);

I didn't test this, and whether this works is up to the implementation
of preg_replace()...

Note if you're planning to put strings into attribute values the ' and "
characters should be escaped as well. (With &apos; and &quot; respectively.)

There is also a caveat; the XML 1.0 spec doesn't allow for some
"special" characters and therefore it is possible that the document is
still not well-formed even if the code does work as I intended. If
you're afraid of encountering characters not allowed to occur in XML 1.0
you should declare the XML version to be 1.1, which allows for almost
all unicode characters. That means you put the string

<?xml version="1.1"?>

first in the document.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top