I currently have a script written in PHP where I connect to a database in phpMyAdmin
, and then parse all of the table values into an XML document.
Here is how the script works:
$xmlBody .= "<XML>";
$sql_news = mysql_query("SELECT * FROM news_table");
$xmlBody .= "<News_Table>";
//this while loop churns out the values of our "news_table" table
while($row_news = mysql_fetch_array($sql_news)){
// Set DB variables into local variables for easier use
$id_news = $row_news["news_id"];
$author_news = $row_news["news_author"];
$time_news = $row_news["news_time"];
$title_news = $row_news["news_title"];
$content_news = $row_news["news_content"];
$desc_news = $row_news["news_description"];
$image_news = $row_news["news_image"];
$xmlBody .= '
<News_Table_Entry>
<DataID>' . $id_news . '</DataID>
<DataAuthor>' . $author_news . '</DataAuthor>
<DataTime>' . $time_news . '</DataTime>
<DataTitle>' . $title_news . '</DataTitle>
<DataContent>' . $content_news . '</DataContent>
<DataDesc>' . $desc_news . '</DataDesc>
<DataImage>' . $image_news . '</DataImage>
</News_Table_Entry>';
} // End while loop
$xmlBody .= "</News_Table>";
mysql_close(); // close the mysql database connection
$xmlBody .= "</XML>";
echo $xmlBody;
?>
How do I create and output this as an external XML file
? I've successfully got this script working, but using all of the methods for writing out to XML isn't working. Using the
echo 'Wrote: ' . $doc->save("/tmp/test.xml") . ' bytes'; // Wrote: 72 bytes
Function isn't working, along with the fwrite function as well. I've been working at trying to figure this out for a few days, but none of the solutions I've been told to try out have worked. Any help or insight would be greatly appreciated!
Have you tried
file_put_contents('/path/to/output.xml', $xmlBody);
This will help you
According to your code, you're already building the XML content yourself. XML files are just regular text files, so in this case you don't need any of the special XML functions that validate and render. Instead, you can simply save your text to the .xml file:
file_put_contents
allows you to forego all the fopen/fwrite functions, so it's the easiest way to write content to disk.On the other hand, if you do want to learn to build a structured XML document with all the bells and whistles of consistency, look up
SimpleXML
orXMLWriter
. A little more overhead that way, but doing all the markup by hand can be unwieldy, especially when one typo can invalidate your whole document.Just to understand, does your
echo $xmlBody;
line at least work as expected?And if you are trying to use the XML file somewhere without success, then note you're missing the XML header as the first line of the XML file.
Note that depending on the data in your database, this header may need to specify a wider encoding such as UTF-16. But you should choose what character sets you want to allow in that database.
And what is the trailing
?>
at the end of your code sample?