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".
Related
I'm trying to do some very basic parsing of XML data but am failing miserably.
I have a metadata.xml file as such:
<?xml version="1.0" encoding="UTF-8" ?>
<metadata>
<page>
<filename>products.php</filename>
<title>Best selection of products in Anytown, USA</title>
<description>We sell quality products</description>
</page>
<page>
<filename>services.com</filename>
<title>Great services anywhere within Anytown</title>
<description>Our services are pretty good</description>
</page>
</metadata>
I'm attempting to get a result for a specific XML entry using the code below:
<?php
$str = simplexml_load_file("metadata.xml") or die("Couldn't load file");
$data = new SimpleXMLElement($str);
// Find the element with specific filename
$nodes = $data->xpath('//metadata/page/filename[.="products.php"]/parent::*');
$result = $nodes[0];
echo "Title: " . $result->title . "\n";
echo "Description: " . $result->description . "\n";
?>
This results in an error:
Warning: SimpleXMLElement::__construct(): Entity: line 4: parser error : Start tag expected, '<' not found in /var/www/html/php_xml_test.php on line 10
Fatal error: Uncaught Exception: String could not be parsed as XML in /var/www/html/php_xml_test.php:10 Stack trace: #0 /var/www/html/php_xml_test.php(10): SimpleXMLElement->__construct('\n\t\n\t\n') #1 {main} thrown in /var/www/html/php_xml_test.php on line 10
If I load the content of the XML file right into the php file everything works fine.
I've read through a bunch of related posts here but can't figure out where I'm going wrong.
Thanks!
As per http://php.net/manual/en/simplexmlelement.construct.php I adjusted the code like that:
<?php
$data = new SimpleXMLElement('metadata.xml', 0, TRUE);
// Find the element with specific filename
$nodes = $data->xpath('//metadata/page/filename[.="services.php"]/parent::*');
$result = $nodes[0];
echo "Title: " . $result->title . "\n";
echo "Description: " . $result->description . "\n";
?>
I have a dynamic form that generates a xml file. The user can add add as many as they want. When the user clicks submit to generate the file, all entries should be written to the xml file.
Unfortunately right now, only the last entry is getting written. I know i need a loop statement but I've having issues.
Here's the form.php --> https://jsfiddle.net/jdarville/mbfjmd02/9/
And here's the save.php(i only included the important parts):
<?php
if(isset($_POST['submit'])){
$message0 = '<?xml version="1.0" encoding="UTF-8"?>';
foreach($_POST['howmany'] as $item_number){
$item_number = $item_number;
}
for($x=1;$x<=$item_number;$x++){
//echo $_POST["templateid".$x];
$message2 = '<Template tid="'. $_POST["templateid".$x].'" gid="000">
<OriginalKey>Queues/Scan</OriginalKey>
<Params>
}
for($x=1;$x<=$item_number;$x++){
$message2 = '</FileFormatInformation>
<StorePath>'. $_POST["uncpath".$x].'</StorePath>
<UserName>'.$_POST["username".$x].'</UserName>
<Password>'.$_POST["password".$x].'</Password>
</SMBStoreParameter>
<caption2>'.$_POST["scantoname".$x].'</caption2>
<userName />
}
}
$file = fopen("test.xml","w");
echo fwrite($file,"$message0 $message1 $message2 ");
fclose($file);
?>
Looks like $message2 = needs to be $message2 .= (that's dot equals)
<?php
if (isset($_POST['submit']))
{
$message0 = '<?xml version="1.0" encoding="UTF-8"?>';
$item_number = intval($_POST['howmany']);
for ($x = 1; $x <= $item_number; $x++)
{
$message1.= '<Template tid="' . $_POST["templateid" . $x] . '" gid="000"> <OriginalKey>Queues/Scan</OriginalKey> <Params>';
}
for ($x = 1; $x <= $item_number; $x++)
{
$message2.= '</FileFormatInformation> <StorePath>' . $_POST["uncpath" . $x] . '</StorePath> <UserName>' . $_POST["username" . $x] . '</UserName> <Password>' . $_POST["password" . $x] . '</Password></SMBStoreParameter><caption2>' . $_POST["scantoname" . $x] . '</caption2><userName />';
}
$file = fopen("test.xml", "w");
echo fwrite($file, "$message0 $message1 $message2 ");
fclose($file);
}
?>
Your xml is not valid because some tags have not been closed and some have not been opened below are some invalid xml tags.
<Params> has not been closed.
</FileFormatInformation> has not been opened.
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).
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.