I need to add article for each month in xml
file using PHP xmlwriter
:
$sql = \"SELECT *,YEAR(FROM_UNIXTIME(timestamp)) AS YEAR,
You are overwriting your XML with each loop. Consider starting document with root and closing document outside the foreach
loop:
$writer->openURI('./cache/xmls/posts-'.$news['MONTH'].'-'.$news['YEAR'].'.xml');
$writer->startDocument('1.0','UTF-8');
$writer->setIndent(4);
$writer->startElement('urlset');
foreach ($newsdata as $news){
$writer->startElement('url');
$writer->writeElement('loc',$news['title']);
$writer->endElement();
}
$writer->endElement();
$writer->endDocument();
$writer->flush();
Your problem is in the query:
$sql = "SELECT *,YEAR(FROM_UNIXTIME(timestamp)) AS YEAR,
MONTH(FROM_UNIXTIME(timestamp)) AS MONTH
FROM ".NEWS_ARTICLES." GROUP BY YEAR, MONTH ORDER BY YEAR DESC, MONTH ";
Most databases other than MySQL would reject this query, because you're grouping on 2 fields whilst selecting many fields.
The group by year, month
will only display a single (random) row from a month and hide all the others.
The solution is to drop the group by
clause entirely and rewrite the query like so:
$sql = "SELECT *,YEAR(FROM_UNIXTIME(timestamp)) AS YEAR,
MONTH(FROM_UNIXTIME(timestamp)) AS MONTH
FROM ".NEWS_ARTICLES." ORDER BY YEAR DESC, MONTH ASC";
Remark
It's odd that you don't have a WHERE
clause. Do you really want to select all articles every time?
A better approach would be to limit the number of articles selected in the query by some filter.
It's always faster to filter in the database rather than in php.