开发者

PHP: $_POST array to XML file and display results

I'm creating a "Madlibs" page where visitors can create funny story things online. The original files are in XML format with the blanks enclosed in XML tags

(Such as blablabla <PluralNoun></PluralNoun> blablabla <Verb>开发者_StackOverflow社区</Verb> ).

The form data is created using XSL and the results are saved using a $_POST array. How do I post the $_POST array between the matching XML tags and then display the result to the page? I'm sure it uses a "foreach" statement, but I'm just not familiar enough with PHP to figure out what functions to use. Any help would be great.

Thanks, E


I'm not sure if I understood your problem quite well, but I think this might help:

// 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";
}


Here is PHP foreach syntax. Hope it helps

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

and here is the code to loop thru your $_POST variables:

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
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜