使用PHP脚本填写XML

时间:2010-04-08 16:29:59

标签: php xml forms

我们都熟悉在HTML页面中“嵌入”PHP脚本来执行显示表单结果等任务,但是如何以显示 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”。任何帮助或教程将不胜感激。

7 个答案:

答案 0 :(得分:2)

您可以将第一行更改为:

<?php echo '<?xml...'; ?>

可以解决问题,如果你愿意,你也可以解开php短标签。

您还可以执行以下操作:

<?php
$body = $_GET['Body'];
$fromPh = $_GET['From'];
echo <<<XMLCODE
<?xml version='1.0' ?>
<Response>
  <msg>Your number is: $fromPh, and you typed: $body.</Msg>
</Response>
XMLCODE;
?>

答案 1 :(得分:1)

您需要在第一个问号与xml之间没有空格:PHP会看到<?,并假设您打算将其作为<?php的简写。

this tutorial on embedding PHP中查看几个段落:

  

XML处理指令是嵌入在XML文档中的命令,供某些应用程序处理。所有XML处理指令都采用以下形式:

     

&lt;?应用程序的appname信息?&gt;

     

请注意,该语句使用嵌套括号和问号打开和关闭,并且所引用的应用程序的名称必须在第一个问号后面,并且前面没有空格。应用程序的信息可以是简短的声明,或者在PHP的情况下,可以继续页面和页面。

重点是我的。

答案 2 :(得分:1)

模板化XML和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声明将使其绊倒。这就是导致错误的原因。

虽然您可以通过禁用短标记来解决此问题,但最好删除<?xml声明,或者也可以删除<声明。无论如何,没有理由在XML文件中包含XML声明(除非您使用的是XML 1.1,或者不是UTF-8的字符编码,这通常是您要避免的。)

就像在HTML中一样,您需要在属性值中转义&htmlspecialchars个字符(和引号),否则您的标记会被破坏。 echo htmlspecialchars与XML一样适用于XML。 (您可能希望定义一个名称较短的函数来执行{{1}},以减少输入。)

答案 3 :(得分:1)

使用PHP的原生XML类(http://www.php.net/manual/en/book.xmlwriter.php),它还将为您提供必要的数据转发等:

<?php

// Your datas from somewhere
$fromPh = '867-5309';
$body = 'The quick brown fox jumped over the <properly encoded?> dog.';

$writer = new XMLWriter();

$writer->openMemory();
$writer->setIndent(true);
$writer->setIndentString(' ');
$writer->startDocument('1.0', 'UTF-8');
$writer->startElement('Response');
$writer->writeElement('Msg', 'Your number is: '.$fromPh.', and you typed: '.$body);
$writer->endElement();
$writer->endDocument();

print $writer->outputMemory();

输出:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
 <Msg>Your number is: 867-5309, and you typed: The quick brown fox jumped over the &lt;properly encoded?&gt; dog.</Msg>
</Response>

答案 4 :(得分:0)

删除<? xml之间的空格,使其<?xml

答案 5 :(得分:0)

function genOutput() {
$output = header("Content-type: text/xml");
$output.= "<container>\n";
$output.= "<title>".$title."</title>\n";
$output.= "<text>".$text."</text>\n";
$output.="</container>\n";
return $output;
}

答案 6 :(得分:0)

echo echo应为echo。学习基本语法。