To operate xml documents in php, we can directly call the DOMDocument class or use the simplexml_load_string class for operations. these functions do not need to be loaded and are directly used. the PHP script reads the most primitive XML... to operate xml documents in php, we can directly call the DOMDocument class or use the simplexml_load_string class for operations. these functions do not need to be loaded and are directly used.
The PHP script reads the most primitive XML and the most stupid method. the code is as follows:
$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, and fast. the code is as follows:
$xmlData = file_get_contents('test.xml'); $xml = simplexml_load_string($xmlData); $xmlArr = objectToArray($xml);
The code of the objectToArray function 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; }
The preceding section describes how to read and write an xml instance. the code is as follows:
$ Arr = array ('id' => 1, 'web' => 'good script', 'weburl' =>' http://www.phprm.com '), Array ('id' => 2, 'web' => 'php script', 'weburl' =>' http://www.phprm.com /'), Array ('id' => 3, 'web' => 'javascript script', 'weburl' =>' http://www.phprm.com /'), Array ('id' => 4, 'web' => 'JS script', 'weburl' =>' http://www.phprm.com /'), Array ('id' => 5, 'web' => 'php script example', 'weburl' =>' http://www.phprm.com /'), Array ('id' => 5, 'web' => 'javascript script example', 'weburl' =>' http://www.phprm.com /');/* Use dom to generate xml. Note that the generated xml contains no spaces. */$ 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 );
Tutorial link:
Reprint at will ~ However, please keep the tutorial address★