读取并将xml元素放入列表中

时间:2014-04-04 16:35:22

标签: php xml xml-parsing

<Data>
    <List>
    <ID>1</ID>
    <Name>Peter</Name>
    <Contact>Mobile</Contact>
    <Address>US</Address>
    </List>
    .
    .
    .
</Data>

我有一个巨大的xml格式;我想读取xml并将xml元素放入列表中。

我们如何在列表中读取和放置元素? 这是我尝试阅读的代码,但是如何将其放入collection.please指南

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>


<body>
<?php
$file = "note2.xml";
$map_array = array(
    "BOLD"     => "B",
    "EMPHASIS" => "I",
    "LITERAL"  => "TT"
);

function startElement($parser, $name, $attrs) 
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "<$map_array[$name]>";
        if (strpos((string) $movies->movie->title ,"PHP")!==false) {
    print 'My favorite movie.';
}
else{
    print 'new one';
    }
        echo "<br />";
    }
}

function endElement($parser, $name) 
{
    global $map_array;
    if (isset($map_array[$name])) {
        echo "</$map_array[$name]>";
                echo "<br />";
    }
}

function characterData($parser, $data) 
{
    echo $data;
}

$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 (!($fp = fopen($file, "r"))) {
    die("could not open XML input");
}

while ($data = fread($fp, 4096)) {
    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)));
    }
}
xml_parser_free($xml_parser);
?>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

将其设为simplexml对象:

$xml = simplexml_load_string($x); // assuming XML in $x

然后访问它:

echo $xml->List[1]->Name;

循环:

foreach ($xml->List as $list)
    echo $list->Name;

看到它有效:https://eval.in/132123

阅读PHP.net上的SimpleXml手册