views:

104

answers:

1

I'm trying to write a parser for a xml postback listener, but can't seem to get it to dump the xml for a sample. The API support guy told me to use 'DOMDocument', maybe 'SimpleXML'? Anyways here's the code: (thanks!)

<?php
$xml_document = file_get_contents('php://input');
$doc = new DOMDocument();
$doc->loadXML($xml_document);
$doc->save("test2/".time().".sample.xml").".xml");
?>
+2  A: 

How about use this to create an XML file?

/**
 * Will output in a similar form to print_r, but the nodes are xml so can be collapsed in browsers
 *
 * @param mixed $mixed
 */
function print_r_xml($mixed)
{
    // capture the output of print_r
    $out = print_r($mixed, true);

    // Replace the root item with a struct
    // MATCH : '<start>element<newline> ('
    $root_pattern = '/[ \t]*([a-z0-9 \t_]+)\n[ \t]*\(/i';
    $root_replace_pattern = '<struct name="root" type="\\1">';
    $out = preg_replace($root_pattern, $root_replace_pattern, $out, 1);

    // Replace array and object items structs
    // MATCH : '[element] => <newline> ('
    $struct_pattern = '/[ \t]*\[([^\]]+)\][ \t]*\=\>[ \t]*([a-z0-9 \t_]+)\n[ \t]*\(/miU';
    $struct_replace_pattern = '<struct name="\\1" type="\\2">';
    $out = preg_replace($struct_pattern, $struct_replace_pattern, $out);
    // replace ')' on its own on a new line (surrounded by whitespace is ok) with '</var>
    $out = preg_replace('/^\s*\)\s*$/m', '</struct>', $out);

    // Replace simple key=>values with vars
    // MATCH : '[element] => value<newline>'
    $var_pattern = '/[ \t]*\[([^\]]+)\][ \t]*\=\>[ \t]*([a-z0-9 \t_\S]+)/i';
    $var_replace_pattern = '<var name="\\1">\\2</var>';
    $out = preg_replace($var_pattern, $var_replace_pattern, $out);

    $out =  trim($out);
    $out='<?xml version="1.0"?><data>'.$out.'</data>';

    return $out;
}

Im my application I posted all of the $_POST variables to it:

$handle = fopen("data.xml", "w+");
$content = print_r_xml($_POST);
fwrite($handle,$content);
fclose();
Kieran Andrews
thanks Kieran! I tried your method for dumping post data to a xml file but it didn't work.. would it fail because the data is already being posted in XML?
Mikey1980
As per the other comment on the post, couldnt you then just save this input to a file?
Kieran Andrews
I had to use "php://input" instead of $_POST--it was an SSL cert problem why the XML posts were failing-ya I can just save it but I will be parsing elements at some point anyways.
Mikey1980