使用PHP脚本填写XML [英] Using PHP script to fill in XML
问题描述
我们都熟悉HTML页面中的嵌入" PHP脚本来执行诸如显示表单结果之类的任务,但是如何以显示 XML 的方式完成呢?
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?
例如,如果我写了:
<?xml version='1.0' ?>
<Response>
<?php
$body = $_GET['Body'];
$fromPh = $_GET['From'];
echo "<Msg>Your number is: $fromPh, and you typed: $body.</Msg>"
?>
</Response>
我收到一条消息,指出解析错误,第1行出现意外的T_STRING" .任何帮助或教程都将不胜感激.
I get a message that states "parse error, unexpected T_STRING on line 1". Any help or tutorials would be appreciated.
推荐答案
对XML和HTML进行模板化没有太大区别.
There is no big difference between templating XML and HTML.
<Response>
<Msg>
Your number is: <?php echo htmlspecialchars($_GET['From']); ?>
and you typed: <?php echo htmlspecialchars($_GET['Body']); ?>
</Msg>
</Response>
如果您的PHP安装被配置为允许将短标签"(即,仅<?
本身而不是<?php
)作为PHP代码,则XML声明会将其绊倒.这就是导致您出错的原因.
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.
虽然可以通过禁用短标签来解决该问题,但最好还是删除<?xml
声明.无论如何,没有理由在XML文件中包含XML声明(除非您使用的是XML 1.1,或者通常不希望使用的字符编码不是UTF-8).
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).
就像在HTML中一样,您需要转义<
和&
字符(以及属性值中的引号),否则标记将被破坏. htmlspecialchars
对于XML和HTML都适用. (您可能想使用一个较短的名称定义一个函数来执行echo htmlspecialchars
,以减少键入.)
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 do echo htmlspecialchars
, to cut down on typing.)
这篇关于使用PHP脚本填写XML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!