Generate XML from PHP via SQL - php

i have a error when running this code .. i run fine when there is no special characteres in database. if its has special characters then i got the error please solve me i am very thankful.
Following Error are occured when any special charachers in database like " ' & ? " i don't why those error come .. and i am not using DOM or XMLWrite just simple create the xml via file, and clerify 1 thing that CDDATA also not working for my code i check it. Please tell me some thing how could i make the xml with error less..
following are the code:
$file= fopen("../xml/{$productID}.xml" , "w");
$_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
$_XML = "<!DOCTYPE Server SYSTEM \"opt/pdos/etc/pdoslrd.dtd\">";
$_xml .="<productsnode>";
while ($row = mysql_fetch_array($productQuery, MYSQL_ASSOC)) {
$_xml .=" <product>";
$_xml .=" <productID>" . $row['productID'] . "</productID>";
$_xml .=" <productName>" . htmlspecialchars($row['productName']) . "</productName>";
$_xml .=" <productDescription>" . htmlspecialchars($row['productDescription']) . "</productDescription>";
$_xml .=" <productPicture>" . htmlspecialchars($row['productPic']) . "</productPicture>";
$_xml .=" <category>";
$_xml .=" <categoryID>" . $row['categoryID'] . "</categoryID>";
$_xml .=" <categoryName>" . htmlspecialchars($row['categoryName']) . "</categoryName>";
$_xml .=" <categoryDescription>" . htmlspecialchars($row['categoryDiscription']) . "</categoryDescription>";
$_xml .=" <categoryPicture>" . htmlspecialchars($row['categoryPic']) . "</categoryPicture>";
$_xml .=" <subCategory>";
$_xml .=" <subCategoryID>" . $row['subCategoryID'] . "</subCategoryID>";
$_xml .=" <subCategoryName>" . htmlspecialchars($row['subCategoryName']) . "</subCategoryName>";
$_xml .=" <subCategoryDetail>" . htmlspecialchars($row['subCategoryDescription']) . "</subCategoryDetail>";
$_xml .=" </subCategory>";
$_xml .=" </category>";
$_xml .=" </product>";
}
$_xml .="</productsnode>";
fwrite($file, $_xml);
fclose($file);

wrap your XML in CDATA
<![CDATA[your content here]]>
(This will also take care of specialchars which are not replaced by htmlspecialchars())

Special chars are illegal in xml so you need to wrap everything between CDATA tags
eg:
$_xml .=" <subCategoryName><![CDATA[" . htmlspecialchars($row['subCategoryName']) . "]]></subCategoryName>";
read more at -> http://www.w3schools.com/xml/xml_cdata.asp
your code should be something like:
$_xml .=" <product>";
$_xml .=" <productID><![CDATA[" . $row['productID'] . "]]></productID>";
$_xml .=" <productName><![CDATA[" . htmlspecialchars($row['productName']) . "]]></productName>";
$_xml .=" <productDescription><![CDATA[" . htmlspecialchars($row['productDescription']) . "]]></productDescription>";
$_xml .=" <productPicture><![CDATA[" . htmlspecialchars($row['productPic']) . "]]></productPicture>";
$_xml .=" <category>";
$_xml .=" <categoryID><![CDATA[" . $row['categoryID'] . "]]></categoryID>";
$_xml .=" <categoryName><![CDATA[" . htmlspecialchars($row['categoryName']) . "]]></categoryName>";
$_xml .=" <categoryDescription><![CDATA[" . htmlspecialchars($row['categoryDiscription']) . "]]></categoryDescription>";
$_xml .=" <categoryPicture><![CDATA[" . htmlspecialchars($row['categoryPic']) . "]]></categoryPicture>";
$_xml .=" <subCategory>";
$_xml .=" <subCategoryID><![CDATA[" . $row['subCategoryID'] . "]]></subCategoryID>";
$_xml .=" <subCategoryName><![CDATA[" . htmlspecialchars($row['subCategoryName']) . "]]></subCategoryName>";
$_xml .=" <subCategoryDetail><![CDATA[" . htmlspecialchars($row['subCategoryDescription']) . "]]></subCategoryDetail>";
$_xml .=" </subCategory>";
$_xml .=" </category>";
$_xml .=" </product>";
If that doesn't work it means there is something else, I suggest you copy the error you get and put it in your answer and maybe take a screenshot of what is stored in the database. If you want help give us more details

It is VERY very difficult to tell when you're not posting the exact errors. However, I will try to do an avid guess: check encodings. It's likely that you're using latin-swedish (AKA-ISO 8859-1) on the database and utf8 for the rest... or viceversa. I would recommend using utf8 for everything and saving your time.
Check table encodings, then the connection encoding (mysql_* functions by default could do the connection using ISO-8859-1 and you should use http://php.net/manual/en/function.mysql-set-charset.php in case that is happening), and that should help.
ALSO: Why are you concatenating strings for generating XML? It is a much better idea to do it with proper XML libraries like SimpleXML (please notice there's other libraries, you can check XMLWriter and many others too). Links: http://mx.php.net/manual/en/book.simplexml.php and ... I can't write the other link because I'm a newb in here :) Google is everyone's friend.
If you go to PEAR, there's more stuff.

I am not really answering your question exactly, but perhaps you should take a look at mysql xml abilities. This may depend upon your mysql version, and especially if you could possibly use the CLI methods to access your sql.
The article mentioned does describe the slightly more convoluted means of getting xml via sql selects though which worked for me on 5.0.67 (win32).

Related

Adding PHP Line Spaces In Codeigniter

I am trying to write file but just need to work out best way to make some gaps/spaces between some code “[‘default’][‘hostname’]” space . ‘=’ . space “‘localhost’”can not work it out.
At the moment when reload page it produces $db['default']['hostname']='localhost'; but need gap/space $db['default']['hostname'] = 'localhost';
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Welcome extends CI_Controller {
public function index(){
$output = '<?php' . "\n";
$output .= "\n";
$output .= '// DB' . "\n";
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
$file = fopen(APPPATH . 'config/database-test.php', 'w');
fwrite($file, $output);
fclose($file);
$this->load->view('welcome_message');
}
}
$output .= '$db' . "['default']['hostname']" space . '=' . space "'localhost'". ";" . "\n";
This line has syntax errors because you're missing the concat operator before the first space and after the second one (whatever the space is meant to be).
Instead of complicating things, why don't you just write this and avoid the concat hell:
$output .= '$db' . "['default']['hostname'] = 'localhost';\n";
I think I have found answer to make gap . " " . seems to do the trick.
$output .= '$db' . "['default']['hostname']" . " " . '=' . " " . "'localhost'". ";" . "\n";
As an additional note, I see you are writing a config file to be processed later.
I have found output buffering and var_export to do this job exceptionally well.
ob_start();
var_export($config);
$out = ob_get_clean();
then
fwrite($f, '$config = '.$out.';'); etc...
http://us3.php.net/manual/en/function.ob-get-clean.php
http://us3.php.net/manual/en/function.var-export.php
basically this will turn an array into a parse-able string such as
array(
'default'=>array(
'hostname'=>'localhost',
'user' => 'user', ///etc
)
)
then just add the variable part and the ending semi-colon
if you plan to do multiple values this would be a much cleaner approach

How do I correctly structure this xml with variables?

How do I correctly structure this XML document. This document will be embedded within a PHP script and send orders to a folder on the server.
Also, can you please look at the FOR EACH loop for products?
Thanks for your help!
(Variables from order form)
$order_id = '1234';
$product_id = '5678';
$prodduct_sku = '0123';
$product_retail = '123.45';
define("FILENAME", "orders/order" . $order_id . ".xml");
$xml_output = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n";
$xml_output .= "<document type="850X-02" timestamp= $timestamp id="123456789>";
$xml_output .= "<order id=" . $order_id .>";
for ($x=0; $x<=100; $x++)
{
$xml_output .= "<line id=" . $x . "quantity=" . $quantity . />";
$xml_output .= "<product id=" . $product_id . "supplier_sku=" . $product_sku . "retail_price=" . $product_retail . />";
}
$xml_output .= "</document>';
// CONVERT THE ARRAY TO A STRING
$str = implode($xml_output);
// WRITE IT INTO THE FILE SYSTEM
file_put_contents(FILENAME, $str);
You don't close your order tag. Add </order> somewhere after the line loop.
Beyond that, you may consider using an IDE that provides robust xml formatting and validation, or you can use a web-based xml validator to verify that the xml you create is valid.
Another tip for testing xml generation code is to get a valid xml sample for the target system, then refine your code until you can generate that example text. Using file diff tools you can quickly identify things like missing tags, elements instead of attributes, or other common errors.

Generate XML with 'SimpleXMLElement' with some empty filelds?

$sitemap .= " " . '<orders>' . "\n" .
"\t" . '<idKlant>' . $id. '</idKlant>' .
"\n\t" . '<emptyfield></emptyfield>' .
"\n\t" . '<date>' . $verzenddatum . '</date>' . //remaining to get
"\n " . '</orders>' . "\n";
For generating XMl, I am using below code
$xmlobj = new SimpleXMLElement($sitemap);
$xmlobj->asXML("orders.xml");
Output of orders.xml
<orders>
<idKlant>12</idKlant>
<emptyfield/>
<date>30-12-2012</date>
</orders>
What i want is: for Empty xml field there should be Opening and Closing tag as well
<orders>
<idKlant>12</idKlant>
<emptyfield></emptyfield>
<date>30-12-2012</date>
</orders>
Is it possible? OR should i add black space?
As Rolando Isidoro said you can't do it with SimpleXML. But you can always switch to the DOM. Both extension use the same underlying library and representation, so there is very little overhead.
DOMDocument::saveXML can take libxml options as the second parameter and there is LIBXML_NOEMPTYTAG which does exactly what you want.
e.g.
<?php
$o = new SimpleXMLELement(data());
$docRoot = dom_import_simplexml($o);
echo $docRoot->ownerDocument->savexml($docRoot,LIBXML_NOEMPTYTAG);
function data() {
return '<orders>
<idKlant>12</idKlant>
<emptyfield/>
<date>30-12-2012</date>
</orders>';
}
prints
<orders>
<idKlant>12</idKlant>
<emptyfield></emptyfield>
<date>30-12-2012</date>
</orders>

XML parsing Error

I have written a PHP script to write an XML document but there is an error:
<?php
$db = "unadb";
$connection = mysql_connect("localhost", "root", "") or die("Could not connect.");
$table_name = 'article';
$db = mysql_select_db($db, $connection);
$query = "select * from " . $table_name;
$result = mysql_query($query, $connection) or die("Could not complete database query");
$num = mysql_num_rows($result);
if ($num != 0) {
$file= fopen("results.xml", "w");
$_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\r\n";
$_xml .="<atricle>";
while ($row = mysql_fetch_array($result)) {
$_xml .="\t<page>\r\n";
if ($row["title"]) {
$_xml .="\t<page title=\"" . $row["title"] . "\">\r\n";
$_xml .="\t<source>" . $row["source"] . "</source>\r\n";
$_xml .="\t<kw>" . $row["kw"] . "</kw>\r\n";
$_xml .="\t\t<Url>" . $row["url"] . "</Url>\r\n";
$_xml .="\t\t<author>" . $row["author"] . "</author>\r\n";
$_xml .="\t<status>" . $row["status"] . "</status>\r\n";
$_xml .="\t</page>\r\n";
} else {
$_xml .="\t<page title=\"Nothing Returned\">\r\n";
$_xml .="\t\t<file>none</file>\r\n";
$_xml .="\t</page>\r\n";
} }
$_xml .="</atricle>";
fwrite($file, $_xml);
fclose($file);
echo "XML has been written. View the XML.";
} else {
echo "No Records found";
} ?>
The output is:
<?xml version="1.0" encoding="UTF-8" ?>
<atricle> <page>
<page title="Coming Race">
<source>http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml</source>
<kw>home</kw>
<Url>http://www.uberarticles.com/articles/artsubmit/upreview.php?article_id=580332</Url>
<author>afnan</author>
<status>active</status>
</page>
<page>
<page title="Coming Race">
<source>http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml</source>
<kw>home</kw>
<Url>http://www.uberarticles.com/articles/artsubmit/upreview.php?article_id=580332</Url>
<author>Doctor</author>
<status>active</status>
</page>
</atricle>
I think the XML is OK but there is an error:
error on line 18 at column 11: Opening and ending tag mismatch: page line 0 and atricle
You're creating XML with raw string manipulation. Getting the open and close tags to match (you have two open <page> tags for each close </page> is going to be the first of many problems with escaping the SQL results you're dumping straight into the XML.
Use a library, or you will have to do a very large amount of work to fix lots of corner cases.
Remove this line of code $_xml .="\t<page>\r\n";
while ($row = mysql_fetch_array($result)) {
$_xml .="\t<page>\r\n";
To
while ($row = mysql_fetch_array($result)) {
You have a total of four <page> opening tags, but only two </page> closing ones.
Your output won't work since you're duplicating the <page> element. This should be your output (I've commented what you should omit):
<?xml version="1.0" encoding="UTF-8" ?>
<atricle>
<!-- <page> -->
<page title="Coming Race">
<source>http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml</source>
<kw>home</kw>
<Url>http://www.uberarticles.com/articles/artsubmit/upreview.php?article_id=580332</Url>
<author>afnan</author>
<status>active</status>
</page>
<!-- <page> -->
<page title="Coming Race">
<source>http://www.public-domain-content.com/books/Coming_Race/C1P1.shtml</source>
<kw>home</kw>
<Url>http://www.uberarticles.com/articles/artsubmit/upreview.php?article_id=580332</Url>
<author>Doctor</author>
<status>active</status>
</page>
</atricle>
As everyone else has said, the double pages are doing you in. Also, while it's not causing you any problems, your overall container is "atricle" and not "article".

How to replace invalid characters in XML using Javascript or PhP

Need help here for the following:
Running PhP, javascript, MySQL, XML.
1) Retrieving file from MySQL and stored it onto XML file.
2) Use javascript function to load XML file (that stored those data).
3) It produces invalid characters in XML file.
STEP 1 : Sample of the code in PhP -> Loading MySQL DB to store data onto XML file
$file= fopen("MapDeals2.xml", "w");
$_xml ="<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n";
$_xml .="<MAP>\n";
while($row1_ThisWeek = mysql_fetch_array($result1_ThisWeek)) {
$rRName = $row1_ThisWeek['Retailer_Name'];
$rRAddress = $row1_ThisWeek['Retailer_Address1'];
$rRAddressPostCode = $row1_ThisWeek['Retailer_AddressPostCode1'];
//} commented out from the original
$_xml .= "<DEAL>\n";
$_xml .= "<DealDescription>" . $d_Description . "</DealDescription>\n";
$_xml .= "<DealURL>" . $d_URL . "</DealURL>\n";
$_xml .= "<DealRName>" . $rRName . "</DealRName>\n";
$_xml .= "<DealRAddress>" . $rRAddress . "</DealRAddress>\n";
$_xml .= "<DealRPostCode>" . $rRAddressPostCode . "</DealRPostCode>\n";
$_xml .= "</DEAL>\n";
}
//} commented out from the original
$_xml .="</MAP>\n";
fwrite($file, $_xml);
fclose($file);
STEP 2 : Sample of the code in Javscript -> Loading XML file
xhttp.open("GET","Test2.xml", false);
xhttp.send("");
xmlDoc=xhttp.responseXML;
var x=xmlDoc.getElementsByTagName("Employee");
parser = new DOMParser();
xmlDoc = parser.parseFromString("MapDeals2.xml", "text/xml");
for (i=0;i<x.length;i++)
{
// alert ('Generating FOR loop');
var d1 = x[i].getElementsByTagName("EmployeeDescription")[0].childNodes[0].nodeValue;
var e1 = "<br></br>";
.
.
.
}
Is there a solution for the above? Looking forward to hear from you soon.
Cheers
It probably is a charset problem. Your MySQL connection has encoding iso-8859-1 or something like that, while the XML is expected to be in UTF8. You have to convert it somewhere.

Categories