2015-01-21 13:06
浏览 57


I have the following XML Document :

<TIMESTAMP>21/01/2015 10:37:22</TIMESTAMP>

When i run the following code, its gives me all of the details from the XML sheet into a centered list, showing just the inners of the tags. Here is the code:


 * PHP XML Parser
 * Map XML to HTML
$file = "";
$map_array = array(
    "BOLD" => "B",
    "EMPHASIS" => "I",
    "LITERAL" => "TT"
echo "<center>";
//setting the first callable function needed
//by xml_set_element_handler
function startElement($parser, $name, $attrs) {
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";

//setting the second callable function needed
//by xml_set_element_handler
function endElement($parser, $name) {
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";

function characterData($parser, $data) {
    echo $data . '<br />';

//creating a new xml parser
$xml_parser = xml_parser_create();
// use case-folding so we are sure to find the tag in $map_array
xml_parser_set_option($xml_parser, XML_OPTION_CASE_FOLDING, true);
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "characterData");
//if the xml can't be open then stop the script
if (!($fp = fopen($file, "r"))) {
    die("could not open XML input");

while ($data = fread($fp, 4096)) {
    //opening the xml and parsing the elements
    if (!xml_parse($xml_parser, $data, feof($fp))) {
        die(sprintf("XML error: %s at line %d", xml_error_string(xml_get_error_code($xml_parser)), xml_get_current_line_number($xml_parser)));

It shows every detail from the external XML document. I want it to only display < DVLA > items < VRM >< MANUFACTURER >< MODEL >< COLOUR > instead of pulling ALL the items from the questioned XML Sheet.

Thanks for reading!

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • douyinjiao9351 2015-01-21 21:56

    If the structure of the XML is always the same, you could simply iterate:

    $xml = simplexml_load_string($x); // assume XML in $x
    foreach ($xml->DATA->DVLA as $d) {
        echo $d->VRM . PHP_EOL;
        echo $d->MANUFACTURER . PHP_EOL;
        echo $d->MODEL . PHP_EOL;
        echo "--------------------" . PHP_EOL;

    If the XML contained more than one <DVLA>, they will all be listed.

    See it working:

    解决 无用
    打赏 举报

相关推荐 更多相似问题