Home > php教程 > php手册 > body text

PHP DOMDocument实现XML读写操作

WBOY
Release: 2016-05-25 16:42:06
Original
1333 people have browsed it

在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);
Copy after login

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

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

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;    
}
Copy after login

上面讲到了读取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);
Copy after login


教程链接:

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!