simplexml_load_string(data,classname,options,ns,is_prefix);
$string = <<<XML
<?xml version='1.0'?>
<document>
<cmd>login</cmd>
<login>imdonkey</login>
</document>
XML;
$xml = simplexml_load_string($string);
print_r($xml);
SimpleXMLElement Object ( [cmd] => login [login] => imdonkey )
$string = <<<XML
<?xml version='1.0'?>
<document>
<cmd>login</cmd>
<login>imdonkey</login>
</document>
XML;
$xml = simplexml_load_string($string);
$arr = toArray($xml);
print_r($arr);
echo $arr['cmd'];
function toArray($object)
{
$object = json_decode(json_encode($object), true);
return $object;
}
simplexml_load_string($string, null, LIBXML_NOCDATA);
$string = <<<XML
<?xml version='1.0'?>
<document>
<cmd><![CDATA[login]]></cmd>
<login><![CDATA[imdonkey]]></login>
</document>
XML;
$xml = simplexml_load_string($string, null, LIBXML_NOCDATA);
var_dump($xml);
<?xml version="1.0" encoding="utf-8"?>
<collection>
<cd>
<title type="hk">港台明星</title>
<artist>刘德华</artist>
<year>1995</year>
</cd>
<cd>
<title>大陆演员</title>
<artist>范冰冰</artist>
<year>1997</year>
</cd>
</collection><?xml version="1.0" encoding="utf-8"?>
<collection>
<cd>
<title type="hk">港台明星</title>
<artist>刘德华</artist>
<year>1995</year>
</cd>
<cd>
<title>大陆演员</title>
<artist>范冰冰</artist>
<year>1997</year>
</cd>
</collection>
<?php
$items=array();
$reader=new XMLReader();
$reader->open('collection.xml', 'utf-8');
while ($reader->read()){
//get current data
if($reader->name=="cd" && $reader->nodeType==XMLReader::ELEMENT){
$item=[];
while($reader->read() && $reader->name !="cd" ){
if($reader->nodeType!=XMLReader::ELEMENT)continue;
$name=$reader->name;
$value=$reader->readString();
$item[$name]=$value;
}
$items[]=$item;
}
}
$reader->close();
print_r($items);
<?php
$file = "collection.xml";
$depth = array();
function startElement($parser, $name, $attrs)
{
global $depth;
/*
for ($i = 0; $i < $depth[$parser]; $i++) {
echo " ";
}*/
//echo "$name\n";
print_r($attrs);
//$depth[$parser]++;
}
function endElement($parser, $name)
{
global $depth;
//$depth[$parser]--;
}
function data($parser, $data) {
var_dump($data);
}
$xml_parser = xml_parser_create('UTF-8');
xml_parser_set_option ( $xml_parser , XML_OPTION_SKIP_WHITE , 1 ) ;
xml_parser_set_option ( $xml_parser , XML_OPTION_CASE_FOLDING , 0 ) ;
xml_set_element_handler($xml_parser, "startElement", "endElement");
xml_set_character_data_handler($xml_parser, "data");
$fp = fopen($file, "r");
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);