Hi,
I have problem (i think) of using xml_parse. The ones I've seen so far reads in xml files. I need to parse a string which is in xml format (an output from another command). Can anyone help me please???
something like this would be nice
$str = shell_exec(command to output in xml format);
xml_parse($xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler ($xml_parser, "characterData");
xml_parse($xml_parser, $str, feof($fp))
or die(sprintf("XML error: %s at line %d",
xml_error_string(xml_get_error_code($xml_parser)),
xml_get_current_line_number($xml_parser)));
xml_parser_free($xml_parser);
string to xml?
Moderator: General Moderators
I'm not quite sure what you want to achieve but maybe this example helps
I don't know a good php-xml tutorial to link to so the best I can offer is the online manual at http://php.net/xml
Code: Select all
<?php
$GLOBALS['xml'] = array();
$GLOBALS['xml']['element_level'] = 0;
function startElement($parser, $name, $attribs)
{
if ($GLOBALS['xml']['element_level'])
echo str_repeat("\t", $GLOBALS['xml']['element_level']);
++$GLOBALS['xml']['element_level'];
echo $name, '[';
$attr = array();
foreach($attribs as $key=>$value)
$attr[] = $key.'='.$value;
echo join(',', $attr), "]\n";
}
function endElement($parser, $name)
{
--$GLOBALS['xml']['element_level'];
}
function characterData($parser, $data)
{
echo str_repeat("\t", $GLOBALS['xml']['element_level']+1), $data, "\n";
}
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
//$str = shell_exec(command to output in xml format);
// a dummy-$str for now
$str = '<root><element1 pos="first">contents</element1><element2 pos="last" optional="true">contents</element2></root>';
xml_parse($xml_parser, $str, true);
?>May be of interest, but requires the use of the DOM and PEAR libs and may be a large detraction from your current application, but interesting non-the-less:
http://devshed.com/Server_Side/PHP/XMLTrees/print_html
Regards,
http://devshed.com/Server_Side/PHP/XMLTrees/print_html
Regards,
I got it to work it was just
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler ($xml_parser, "characterData");
xml_parse($xml_parser, $str);
xml_error_string(xml_get_error_code($xml_parser));
xml_get_current_line_number($xml_parser);
xml_parser_free($xml_parser);
$xml_parser = xml_parser_create();
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler ($xml_parser, "characterData");
xml_parse($xml_parser, $str);
xml_error_string(xml_get_error_code($xml_parser));
xml_get_current_line_number($xml_parser);
xml_parser_free($xml_parser);