is it possible to put PHP code inside a XML document to be later executed? For example, can I say
It is possible, but I'd recommend putting it inside of a CDATA block, so you don't have to escape <
and similar characters:
<element>
<![CDATA[
<?php echo date('Y'); ?>
]]>
</element>
If you run the XML file as a PHP script, then yes. The output of the script will be valid XML, but the file that contains the inline PHP will most likely not be valid XML.
Yes.
Use this example code, filenamed 'example.php':
<?php
ob_start();
require_once "relative/path/to/file.xml";
$xml_with_php_values = ob_get_clean();
?>
Put the php in the xml file as how you put in html.
<element value="<?php echo date('Y'); ?> />
To force your webserver to execute PHP inside XML files, change the MIME type of .xml
-files to application/x-httpd-php
, by adding this line to .htaccess
:
AddType application/x-httpd-php .xml
Now all XML files are treated by the webserver the same way as PHP files:
<?xml version="1.0" encoding="UTF-8"?>
<servertime>
<?php
echo date('c');
header('Content-Type: application/xml; charset=utf-8');
?>
</servertime>
Note that the header
-definition is there to correct the MIME type of your file back to application/xml
. Otherwise it would be treated by the browser as HTML, preventing it from displaying a nice DOM tree (or whatever the default XML handling may be...). Even if the file is not intended to be opened in a browser, it's never nice to fake the MIME type of a file, so please don't forget this line ;)
The drawback of this solution: Now all XML files in the access range of your .htaccess
will be treated as php, so you'd have to change the MIME-type of any XML file in the same folder via PHP. Workaround: Move your php-hacked XML and the .htaccess
to a separate folder.
A PHP program can output any kind of content you like, however it will (if used with a web module like mod_php) output with a text/html content type by default, so you will need to do:
<?php
header('Content-Type: application/xml; charset=utf-8');
?>
(Substitute a more appropriate content-type if one is applicable).
You will also need to configure your webserver to recognise that the file should be treated as PHP and not served up as static data. This is usually achieved by giving the file a .php extension. Consult the manual for your webserver and PHP's module for it if you want to use a different file naming convention.