Using PHP to Output XML

<?
    $MySQLPassword = "indian";  
    $HostName = "localhost";    
    $UserName = "monty";

    mysql_connect($HostName,$UserName,$MySQLPassword)
    or die("ERROR: Could not connect to database!");

    mysql_select_db("sachin") or die("cannot select db");

    $keyword = $_POST['keyword'];
    echo $keyword;
   /* Execute the query that performs the actual search in the DB: */
   $result = mysql_query(" SELECT p.page_url AS url,
                           COUNT(*) AS occurrences 
                           FROM page p, word w, occurrence o
                           WHERE p.page_id = o.page_id AND
                           w.word_id = o.word_id AND
                           w.word_word = \"$keyword\"
                           GROUP BY p.page_id
                           ORDER BY occurrences DESC
                           " );

$output = new DOMDocument();
$output->formatOutput = true;
$output = "<loginsuccess>";

for( $i = 1; $row = mysql_fetch_array($result); $i++ )      {


$output .="<person><keyword>".$_POST['keyword']."</keyword><name>".$row['url']."</name><occur>".$row['occurrences']."</occur></person>";
}

$output .= "</loginsuccess>";
print ($output);

?>

      

I am getting the output as XML, but I need to save it in a separate XML file, can anyone help me.

One more question,....

I am using fwrite and am good at writing to a file, but how can I clear the file every time it writes, instead of writing at the end of the file? I need the existing content to be destroyed and written again.

0


a source to share


4 answers


Use fwrite .

EDIT: For truncation use:



$handle = fopen($filename , "wb")

      

when opening. W means open for writing and truncate to 0 length. B stands for binary mode, so Windows doesn't tamper with your line endings.

+4


a source


file_put_contents is the easiest way to dump a line to a file.



+2


a source


Just simple file functions, check them out on PHP.net website.

0


a source


Also, you want you to properly escape the content of the XML file. htmlentities () is a good place to start reading on a topic, or you can just use<![CDATA[ ... ]]>

-2


a source







All Articles