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.
Related
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.
$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>
I currently have a PHP script which when ran outputs an XML file (however as feed.php not feed.xml) I have been told to add this to my .htaccess and it should fix it:
AddType application/x-httpd-php .xml
However for some reason that isn't working.
What I'd ideally like the script to do - when ran is to generate a feed.xml file with the output of its contents, rather than just outputting the contents on the php page.
Here is my code:
<?PHP
include("../config.php");
#// Timetable Clearup Variabls
$yesterday = strtotime('yesterday');
$yesterdow = date('l',$yesterday);
$order = "SELECT * FROM timetable WHERE day = '$yesterdow' ORDER BY time";
$result = mysql_query($order);
$yesterdayd = date('F jS, Y', time()-86400);
//SET XML HEADER
header('Content-type: text/xml');
//CONSTRUCT RSS FEED HEADERS
$output = '<rss version="2.0">';
$output .= '<channel>';
$output .= "<title>Timetable - {$yesterdayd} </title>";
$output .= '<description>Timetable.</description>';
$output .= '<link>http://site.com/</link>';
### $output .= '<copyright>Your copyright details</copyright>';
while ($row = mysql_fetch_array($result)) {
//BODY OF RSS FEED
$output .= '<item>';
$output .= "<description><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['time']) . "</td></description>";
$output .= '</item> ';
}
//CLOSE RSS FEED
$output .= '</channel>';
$output .= '</rss>';
//SEND COMPLETE RSS FEED TO BROWSER
echo($output);
?>
I would suggest not adding .xml in .htaccess to be processed using PHP compiler.
Rather use mod_rewrite to redirect requests to .xml files to php script.
For example:
RewriteEngine On
RewriteRule ^(.*)\.xml$ /rss_feed.php [L,QSA]
I'm trying to create a XML file dynamically trough php, reading DIRS and FILES on a specific directory on my ftp.
So far so god, here's the code:
<?php
$path = ".";
$dir_handle = #opendir($path) or die("Unable to open $path");
function list_dir($dir_handle,$path)
{
while (false !== ($file = readdir($dir_handle))) {
$dir =$path.'/'.$file;
$link =$path.'/';
if(is_dir($dir) && $file != '.' && $file !='..' )
{
$handle = #opendir($dir) or die("unable to open file $file");
$xmlString .= '<' . $file . '>';
list_dir($handle, $dir);
$xmlString .= '</' . $file . '>';
}
elseif($file != '.' && $file !='..' && $file !='ftpteste.php')
{
$xmlString .= '<IMAGE>';
$xmlString .= '<PHOTO>' . $link . '' . $file . '</PHOTO>';
$xmlString .= '</IMAGE>';
}
}
closedir($dir_handle);
}
$xmlString ='<XML>';
list_dir($dir_handle,$path);
$xmlString .="</XML>";
$strXMLhead = '<?xml version="1.0" encoding="UTF-8" ?>';
$xmlString = $strXMLhead . "\n" . $xmlString;
$xmlLoc = "../../interiores/xml/content.xml";
$fileXML = fopen($xmlLoc, "w+") or die("Can't open XML file");
if(!fwrite($fileXML, pack("CCC",0xef,0xbb,0xbf)))
{
print "Error Saving File";
}
else
{
fwrite($fileXML, $xmlString);
print "XML file saved";
}
fclose($fileXML);
?>
The problem is that i'm getting no output on $XmlString running inside the function. If i use Print instead joining the strings it's fine, it does the job. But i need it to be in a variable in order to save to file.
Saving to file it's ok.
It should output something like:
<XML>
<$DIR NAME>
<IMAGE>
<PHOTO>$FILE_NAME</PHOTO>
</IMAGE>
</$DIR NAME>
</XML>
Can anyone help me with this?
thanks in advance,
artur
I think you should take a look at the DomDocument object. It provides an easy way to create a document with nodes (like an xml document). You will be able to avoid your problem with that.
Return the XML you're building from list_dir().
function list_dir($dir_handle,$path)
{
...
$xmlString .= list_dir($handle, $dir);
...
return $xmlString;
}
$xmlString = '<XML>' . list_dir($dir_handle,$path) . '</XML>';
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).