Jump to content

writing to a xml file


maximyus

Recommended Posts

I am attempting to write results from a mysql query into a xml file. Currently I just have the results echo out, but I would like to create a separate file.

[code]
<?
$connection = mysql_connect("localhost", "xxx", "xxx") or die ("Cannot make the connection");
$db = mysql_select_db("word", $connection) or die ("Cannot make the connection");
if(in_array($_POST['select'], array(3,5,10,20))) {
  $sql = "SELECT * FROM Random ORDER BY RAND() LIMIT {$_POST['select']}";
  $result=mysql_query($sql) or die("query failed: $sql - ". mysql_error());
      echo "<?xml version=\"1.0\"?>\n";
    echo "<words>\n";
while($line = mysql_fetch_assoc($result)) {
echo "<item>" . $line["Words"] . "</item>\n";
}
echo "</words>\n";
}
mysql_close($connection);
?>
[/code]

So I tried to use file_put_contents(), but have not had any luck. I tried:

[code]
<?
$connection = mysql_connect("localhost", "xxx", "xxx") or die ("Cannot make the connection");
$db = mysql_select_db("word", $connection) or die ("Cannot make the connection");
if(in_array($_POST['select'], array(3,5,10,20))) {
  $sql = "SELECT * FROM Random ORDER BY RAND() LIMIT {$_POST['select']}";
  $result=mysql_query($sql) or die("query failed: $sql - ". mysql_error());  
while($line = mysql_fetch_assoc($result)) {
file_put_contents('file.xml', $line->asXML());
}
}
mysql_close($connection);
?>
[/code]

I do not get any errors, but the file is not created. If I remove the ->asXML() part it will create the file but only one line is created and it is not in proper xml format so it can not be read. Any help on the proper code would be greatly appreciated.
Link to comment
https://forums.phpfreaks.com/topic/27064-writing-to-a-xml-file/
Share on other sites

A combination of the 2 should do. store contents as you read the table then output with file_put_contents

[code]<?php
$connection = mysql_connect("localhost", "xxx", "xxx") or die ("Cannot make the connection");
$db = mysql_select_db("word", $connection) or die ("Cannot make the connection");
if(in_array($_POST['select'], array(3,5,10,20))) {
  $sql = "SELECT * FROM Random ORDER BY RAND() LIMIT {$_POST['select']}";
  $result=mysql_query($sql) or die("query failed: $sql - ". mysql_error());
      $content = "<?xml version=\"1.0\"?>\n";
    $content .= "<words>\n";
while($line = mysql_fetch_assoc($result)) {
    $content .= "<item>" . $line["Words"] . "</item>\n";
}
$content .= "</words>\n";
}
mysql_close($connection);

file_put_contents('file.xml', $$content);
?>[/code]
Link to comment
https://forums.phpfreaks.com/topic/27064-writing-to-a-xml-file/#findComment-123823
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.