Thursday, April 28, 2011

PHP error in .xml file?

OK firstly, I added this line to my .htaccess file so the php engine parses php code in .xml file:

AddType application/x-httpd-php .php .php3 .phtml .html .xml

After that when I view an .xml file I get this PHP error:

Parse error: parse error, unexpected T_STRING in /var/www/vhosts/mydomain.com/httpdocs/test.xml on line 1

But line 1 is not even php infact this is line 1:

<?xml version="1.0" encoding="utf-8"?>

Can anyone tell me what the problem is?

Thanks.

From stackoverflow
  • that's because < ? is the short opening tag for php.

    try: < ? php echo '< ?xml version="1.0" encoding="utf-8"?>'; ?>

    Without the spaces

    pix0r : I've had problems with even this solution - you may need to do `'; ?>`
    thomasrutter : What pix0r said. The problem with Apikot's answer is the '?>' sequence appearing in the string, whereas in PHP the characters '?>' should never appear even in a string.
    thomasrutter : ... interestingly, PHP's own parser tolerates it. The reason I avoid it is that syntax highlighting text editors or IDEs often don't.
    Andrei Serdeliuc : Out of my experience, php doesn't have any problems with '?>' in a string. Care to elaborate please?
  • Yeah, sad but true, it's the doctype being seen as the PHP opening short tag. You have a few options:

    1. Take XML out of the list of files for PHP to parse in the .htaccess file
    2. Wrap all of your xml declarations in PHP:

      <?php print('<?xml version="1.0" encoding="utf-8"?>'); ?>

    3. Turn off short_open_tag in .htaccess or the php.ini. This means that PHP will only accept <?php as an opening tag and will ignore <?.

    bobince : If you want the XML file to remain well-formed XML even with the PHP inside it, hide the closing ‘?>’. eg. print('');
    danieltalsky : Would this really let it remain a valid XML document on the server side? I don't think having a PHP open tag as the first viable character would do the job. I think if you take this approach you can't make it a valid XML document on the server... only on output.
    bobince : Yes, a PHP open tag in the long form makes an XML Processing Instruction. It's quite valid to have a PI (or Comment) outside the root documentElement.
    bobince : (The main problem encountered when trying to make PHP files also well-formed XML is coming up with alternatives for inserting content into attribute values and optionally-including attributes, since you can't put a PI inside an element or attribute.)
  • Alternative 4, in addition to daniel's: drop the <?xml...?> declaration completely.

    Since ‘1.0’ and ‘utf-8’ are the defaults for XML, it's completely redundant; including the XML declaration here gains you nothing.

0 comments:

Post a Comment