PHP:$ _POST数组到XML文件并显示结果

时间:2011-03-12 00:41:18

标签: php xml arrays forms post

我正在创建一个“Madlibs”页面,访问者可以在线创建有趣的故事。原始文件采用XML格式,空格用XML标记括起来

(Such as blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb> ).

使用XSL创建表单数据,并使用$ _POST数组保存结果。如何在匹配的XML标记之间发布$ _POST数组,然后将结果显示到页面?我敢肯定它使用了“foreach”语句,但我对PHP不太熟悉,无法确定要使用的函数。任何帮助都会很棒。

谢谢, E

2 个答案:

答案 0 :(得分:1)

我不确定我是否理解你的问题,但我认为这可能会有所帮助:

// mocking some $_POST variables
$_POST['Verb'] = 'spam';
$_POST['PluralNoun'] = 'eggs';

// original template with blanks (should be loaded from a valid XML file)
$xml = 'blablabla <PluralNoun></PluralNoun> blablabla <Verb></Verb>';
$valid_xml = '<?xml version="1.0"?><xml>' . $xml . '</xml>';

$doc = DOMDocument::loadXML($valid_xml, LIBXML_NOERROR);
if ($doc !== FALSE) {
    $text = ''; // used to accumulate output while walking XML tree
    foreach ($doc->documentElement->childNodes as $child) {
        if ($child->nodeType == XML_TEXT_NODE) { // keep text nodes
            $text .= $child->wholeText;
        } else if (array_key_exists($child->tagName, $_POST)) {
            // replace nodes whose tag matches a POST variable
            $text .= $_POST[$child->tagName];
        } else { // keep other nodes
            $text .= $doc->saveXML($child);
        }
    }
    echo $text . "\n";
} else {
    echo "Failed to parse XML\n";
}

答案 1 :(得分:0)

这是PHP foreach语法。希望它有所帮助

$arr = array('fruit1' => 'apple', 'fruit2' => 'orange');
foreach ($arr as $key => $val) {
    echo "$key = $val\n";
}

以下是循环通过$ _POST变量的代码:

foreach ($_POST as $key => $val) {
    echo "$key = $val\n";
    // then you can fill each POST var to your XML
    // maybe you want to use PHP str_replace function too
}