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

I have a huge xml in this format; I want to read the xml and put the xml elements into a list.

How can we read and put elements in a list? here is the code which i tried for reading,but how to put that in a collection.please guide

<!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>
user3488008
  • 59
  • 3
  • 10

1 Answers1

0

Make it a simplexml object:

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

Then access it like:

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

Loop:

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

see it working: https://eval.in/132123

Read the SimpleXml Manual on PHP.net

michi
  • 6,565
  • 4
  • 33
  • 56