1

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></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

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.