Jump to content

creating a XML file from MYSQL with PHP


jamesflowers

Recommended Posts

I have the code below , and when I run it on my website , it returns a XML Parsing Error: not well-formed error , which says it has a problem reading the & i think

 

please see http://www.jamesflowersreports.com/php/xml2.php

 

I think it has something to wiht the str_replace as when I change the $row['customerName'] . "</Name>\n"; to $row['customerNumber'] . "</Name>\n"; as a test it works fine , I understand XML cant handle special characters , how would prevent this happening?

 

code as below

 

 

 

$query = "SELECT * FROM customers";
$resultID = mysql_query($query, $linkID) or die("Data not found.");

$xml_output = "<?xml version=\"1.0\"?>\n";
$xml_output .= "<entries>\n";

for($x = 0 ; $x < mysql_num_rows($resultID) ; $x++){
    $row = mysql_fetch_assoc($resultID);
    $xml_output .= "\t<entry>\n";
    $xml_output .= "\t\t<Name>" . $row['customerName'] . "</Name>\n";
        // Escaping illegal characters
        $row['text'] = str_replace("&", "&", $row['text']);
        $row['text'] = str_replace("<", "&lt", $row['text']);
        $row['text'] = str_replace(">", ">", $row['text']);
        $row['text'] = str_replace("\"", """, $row['text']);
    $xml_output.= "\t\t<Number>" . $row['customerNumber'] . "</Number>\n";
    $xml_output.= "\t</entry>\n";
}

$xml_output .= "</entries>";

echo $xml_output;

 

 

regards

 

James

Link to comment
Share on other sites

You could always use CDATA elements

 

cust.xml

<?xml version="1.0" encoding="utf-8" ?>
<customers>
    <Customer>
    <Number>1234</Number>
    <Name><![CDATA[<i>Proctor & Gample</i>]]></Name>
    <Text><![CDATA[<strong>Soap Manufacturers</strong>]]></Text>
    </Customer>
    <Customer>
    <Number>1235</Number>
    <Name><![CDATA[<i>Fleecem & Runn</i>]]></Name>
    <Text><![CDATA[<strong>Financial Advisors</strong>]]></Text>
    </Customer>
</customers>

code

$xml = simplexml_load_file('cust.xml');
foreach ($xml->Customer as $c) {
    echo $c->Number . '<br>';
    echo $c->Name . '<br>';
    echo $c->Text . '<br><br>';
}

output

 

post-3105-0-91407400-1405591015_thumb.png

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.