we are all familiar with "embedding" PHP scripts in HTML pages to do tasks like displaying form results, but how can that be done in a way that displays XML?
For example, if I wrote:
<?xml version='1.0' ?>
<Response>
<?php
$body = $_GET['Body'];
$fromPh = $_GET['From'];
echo "<Msg>Your number is: $fromPh, and you typed: $body.</Msg>"
?>
</Response>
I get a message that states "parse error, unexpected T_STRING on line 1". Any help or tutorials would be appreciated.
remove the space between
<? xml
so its<?xml
You need to not have a space between the first question mark and
xml
: PHP sees the<?
and assumes that you intended that to be shorthand for<?php
.See a few paragraphs down in this tutorial on embedding PHP:
Emphasis was mine.
You could change the first line to:
that would solve the problem, you could also disbale php shorttags if you so desired.
You could also do the following:
There is no big difference between templating XML and HTML.
If your PHP installation is configured to allow “short tags” (ie., just
<?
on its own rather than<?php
) as being PHP code, then the XML Declaration will trip it up. This is what caused your error.Whilst you can fix that problem by disabling short tags, it's probably best to remove the
<?xml
declaration instead or as well. There is no reason to include an XML Declaration in an XML file anyway (unless you're using XML 1.1, or a character encoding that isn't UTF-8, which generally you'd want to avoid).Just as in HTML, you need to escape
<
and&
characters (and quotes, in attribute values) otherwise your markup gets broken.htmlspecialchars
works just as well for XML as it does for HTML. (You may want to define a function with a shorter name to doecho htmlspecialchars
, to cut down on typing.)echo echo
should beecho
. Learn the basic syntax.Use PHP's native XML classes (http://www.php.net/manual/en/book.xmlwriter.php), which also will provide the necessary data escaping etc for you:
Output: