Home  >  Article  >  php教程  >  PHP DOMDocument实现XML读写操作

PHP DOMDocument实现XML读写操作

WBOY
WBOYOriginal
2016-05-25 16:42:061333browse

在php中操作xml文档我们可以直接调用DOMDocument类或使用simplexml_load_string类来操作,这些都不需要加载算是内置函数了,我们直接使用.

PHP脚本读取XML最原始,最笨的方法,代码如下:

$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);

简单,容易,速度快,代码如下:

$xmlData = file_get_contents('test.xml');  
$xml = simplexml_load_string($xmlData);  
$xmlArr = objectToArray($xml);

objectToArray函数代码如下:

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;    
}

上面讲到了读取xml,下面再介绍写xml实例,代码如下:

$arr = array(  
    array('id'=>1,'web'=>'好脚本','webUrl'=>'http://www.phprm.com'),  
    array('id'=>2,'web'=>'PHP脚本','webUrl'=>'http://www.phprm.com/'),  
    array('id'=>3,'web'=>'JavaScript脚本','webUrl'=>'http://www.phprm.com/'),  
    array('id'=>4,'web'=>'js脚本','webUrl'=>'http://www.phprm.com/'),  
    array('id'=>5,'web'=>'PHP脚本示例','webUrl'=>'http://www.phprm.com/'),  
    array('id'=>5,'web'=>'JavaScript脚本示例','webUrl'=>'http://www.phprm.com/')  
);  
/*使用dom生成xml,注意生成的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);


教程链接:

随意转载~但请保留教程地址★

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn