is the most primitive and stupid way for PHP scripts to read XML.
The code is as follows |
Copy Code |
$doc = new DOMDocument ();
$doc->load (' Test.xml ');
$rows = $doc->getelementsbytagname ("DS");
$d = Array ();
$i = 0; foreach ($rows as $row) { $web = $row->getelementsbytagname (' web '); $WEBURL = $row->getelementsbytagname (' Weburl '); $d [$i] [' web '] = $web->item (0)->nodevalue; $d [$i] [' weburl '] = $webUrl->item (0)->nodevalue; $i + +; }
Print_r ($d); |
Simple, easy, fast
The code is as follows |
Copy Code |
$xmlData = file_get_contents (' Test.xml ');
$xml = simplexml_load_string ($xmlData);
$XMLARR = Objecttoarray ($xml);
The Objecttoarray function code is as follows function Objecttoarray ($object) { if (! $object) return "; $result = Array (); $object = Is_object ($object)? Get_object_vars ($object): $object; foreach ($object as $key => $val) { $val = (Is_object ($val) | | | Is_array ($val))? Objecttoarray ($val): $val; $result [$key] = $val; } return $result; } |
Read XML, and then write XML instance
The code is as follows |
Copy Code |
$arr = Array ( Array (' ID ' =>1, ' web ' => ' good script ', ' Weburl ' => ' http://www.111cn.net '), Array (' ID ' =>2, ' web ' => ' php script ', ' Weburl ' => ' http://www.111cn.net/'), Array (' ID ' =>3, ' web ' => ' javascript script ', ' Weburl ' => ' http://www.111cn.net/'), Array (' ID ' =>4, ' web ' => ' js script ', ' Weburl ' => ' http://www.111cn.net/'), Array (' ID ' =>5, ' web ' => ' php script sample ', ' Weburl ' => ' http://www.111cn.net/'), Array (' ID ' =>5, ' web ' => ' javascript script sample ', ' Weburl ' => ' http://www.111cn.net/') ); /* Use DOM to generate XML, noting that there are no spaces in the generated XML. */ $dom =new DOMDocument (' 1.0 ', ' utf-8 ');
$path = "Logs/test.xml";
$data = $dom->createelement (' data ');
$dom->appendchild ($data);
foreach ($arr as $v) { $ds = $dom->createelement (' DS ');
$id = $dom->createattribute (' id ');
$id->nodevalue = $v [' id '];
$ds->setattributenode ($id);
$data->appendchild ($DS);
foreach ($v as $kk => $vv) { ${$kk} = $dom->createelement ($KK);
$value = $dom->createtextnode ($VV);
${$kk}->appendchild ($value);
$ds->appendchild (${$kk});
} }
$dom->savexml ();
$dom->save ($path); |