Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

XML Parsing Error: XML or text declaration not at start of entity

Tags:

php

xml

rss

I have this error in my rss.php

XML Parsing Error: XML or text declaration not at start of entity Location: http://blah.com/blah/blah/site/rss.php Line Number 1, Column 3:
and this is shown underneath the error

<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><item><title>xzfbcbcxv 123</title><description><p>Description for the rss feed</p></description></item></channel></rss>

The

----------------^

is show between the left side of the page and the ?xml line.

In my rss.php I have

<?php header("Content-type: text/xml"); ?>
<?php include("includes/database.php");?>
<?php global $_TWITTER_TABLE, $_HTTP_ADDRESS, $_NEWS_TABLE; ?>
<?php $str = '<?xml version="1.0" encoding="UTF-8"?>'; ?>
<?php $str .= '<rss version="2.0">';?>
<?php
$str.='<channel>';
$sql = "SELECT * FROM $_NEWS_TABLE LIMIT 5";
$result = mysql_query($sql) or die ($sql."".mysql_error());
    while($row = mysql_fetch_object($result)){
        $str.= '<item>';
                $str.= '<title>'.$row->title. '</title>';
                $str.= '<description>'.$row->content. '</description>';
        $str.= '</item>';
}
$str.= '</channel>';
?>
<?php $str .= '</rss>'; 
    echo $str;
?>
like image 279
user3095193 Avatar asked Jan 28 '14 11:01

user3095193


1 Answers

You have a lot of white space before the declaration. You need to remove it. This can be caused by having closing PHP tags followed by spaces or tabs or new line at the end of included files. You can prevent this by just not closing the PHP tags.

Second look, remove all the closing tags at the top of your document:

<?php // make sure that this is the first character in the file, no spaces before it
    header("Content-type: text/xml");
    include("includes/database.php");
    global $_TWITTER_TABLE, $_HTTP_ADDRESS, $_NEWS_TABLE;
    $str = '<?xml version="1.0" encoding="UTF-8"?>';
    $str .= '<rss version="2.0">';
    $str.='<channel>';
    $sql = "SELECT * FROM $_NEWS_TABLE LIMIT 5";
    $result = mysql_query($sql) or die ($sql."".mysql_error());
    while($row = mysql_fetch_object($result)){
        $str.= '<item>';
        $str.= '<title>'.$row->title. '</title>';
        $str.= '<description>'.$row->content. '</description>';
        $str.= '</item>';
    }
    echo $str;

Also, just a note, the mysql_* functions are deprecated due to security problems. You may want to look at mysqli and PDO

like image 50
Matt Avatar answered Oct 20 '22 09:10

Matt