php simpleXML添加CDATA格式数据

 更新时间:2016年11月25日 16:54  点击:1966
我们知道php中的simpleXML没办法直接很方便的添加CDATA格式的数据,这样对我们操作时会有一定的问题,下面我来给各位同学介绍php simpleXML添加CDATA格式数据一种办法。

代码

 代码如下 复制代码

<?php
/**
* to show <title lang="en"><![CDATA[Site Title]]></title>   instead of <title lang="en">Site Title</title>
*
*/
class SimpleXMLExtended extends SimpleXMLElement
  {
  public function addCData($cdata_text)
    {
    $node = dom_import_simplexml($this);
    $no   = $node->ownerDocument;
    $node->appendChild($no->createCDATASection($cdata_text));
    }
  }
$xmlFile    = 'config.xml';
// instead of $xml = new SimpleXMLElement('<sites/>');
$xml = new SimpleXMLExtended('<sites/>');
$site = $xml->addChild('site');
// instead of $site->addChild('site', 'Site Title');
$site->title = NULL; // VERY IMPORTANT! We need a node where to append
$site->title->addCData('Site Title');
$site->title->addAttribute('lang', 'en');
$xml->asXML($xmlFile);
?>

本文章给来大家讲一下关于PHP 下simplexml使用方法,希望通过此文章能提升大家对simplexml操作xml文档的理解,有需要了解的朋友可参考。

PHP XML处理XML代码如下

 代码如下 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<!-- Edited with XML Spy v2007 (http://www.altova.com) -->
<breakfast_menu>
 <food id="1">
  <name>Belgian Waffles</name>
  <price>$5.95</price>
  <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
  <calories>650</calories>
 </food>
 <food id="2">
  <name>Strawberry Belgian Waffles</name>
  <price>$7.95</price>
  <description>light Belgian waffles covered with strawberries and whipped cream</description>
  <calories>900</calories>
 </food>
 <food id="3">
  <name>Berry-Berry Belgian Waffles</name>
  <price>$8.95</price>
  <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
  <calories>900</calories>
 </food>
</breakfast_menu>


php解决xml代码

 代码如下 复制代码

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>使用simpleXML处理XML</title>
</head>

<body>
<table border="1" cellpadding="0" cellspacing="0" width="700">
</tbody>
<tr bgcolor="green">
<th width="5%">&nbsp;</th>
<th width="20%">name</th>
<th width="10%">price</th>
<th width="55%">description</th>
<th width="10%">calories</th>
</tr>
<?php
 // 使用simpleXML处理XML

 $xml = simplexml_load_file('./simple.xml');
 //var_dump($xml);
 //echo $xml->getName();
 //var_dump($xml->children());
 $record = '';
 foreach ($xml->children() as $child)
 {
  $record .= '<tr><td>'. $child->attributes(). '</td>';
  foreach ($child->children() as $item)
  {
   //var_dump($child);
   $record .= '<td>'. $item .'</td>';
  }
  $record .= '</tr>';
 }
 echo $record;
?>
</tbody>
</table>
</body>
</html>

将XML转换为数组结构

 代码如下 复制代码

private function change_simple_xml_to_array($obj){
  $i = 0;
  //从根节点下的二层子节点开始遍历
  foreach($obj->children() as $value){
    //如果发生同级、同标签名的情况,则加一维数组;
    if(isset($last_name) && $value->getName()==$last_name){
      //出现同名发现第二个,则推入第二维数组;
      if($i==1) $arr[$last_name]=array($arr[$last_name]);
      //遍历子节点;
      array_push($arr[$last_name],$this->change_simple_xml_to_array($value));
    }else{
      $last_name = $value->getName();
      if(count($value->children())==0) $arr[$last_name] = $value."";
      else $arr[$last_name] = $this->change_simple_xml_to_array($value);
    }
    $i++;
  }
  return $arr;
}

 

 

 

——————XML文档——————

 


<?xml version="1.0" encoding="utf-8"?>
<use>
  <login id="1">
    <user>bddg</user>
    <pas>abcdefg</pas>
    <permission><fdsa>5</fdsa></permission>
    <online_time>2</online_time>
  </login>
  <login id="2">
    <user>baidongdaogu</user>
    <pas>aaa</pas>
    <permission>1</permission>
    <online_time>2</online_time>
  </login>
  <login id="3">
    <user>baidongdaogu</user>
    <pas>aaa</pas>
    <permission>1</permission>
    <online_time>2</online_time>
  </login>
</use>


————转换后的数组————

Array
(
  [login] => Array
    (
      [0] => Array
        (
          [user] => bddg
          [pas] => abcdefg
          [permission] => Array
            (
              [fdsa] => 5
            )

          [online_time] => 2
        )

      [1] => Array
        (
          [user] => baidongdaogu
          [pas] => aaa
          [permission] => 1
          [online_time] => 2
        )

      [2] => Array
        (
          [user] => baidongdaogu
          [pas] => aaa
          [permission] => 1
          [online_time] => 2
        )
    )
)

下面我先是介绍一个朋友自己写的一个操作xml文档程序,然后再介绍了php中一个自带的解析xml文档的函数功能,有需要的朋友可参考。
 代码如下 复制代码

 

/*
<?xml version="1.0" encoding="UTF-8"?>
<班级>
<学生 number="101">
<名字>孙悟空</名字>
<名字>孙行者</名字>
<年龄>猴精猴精</年龄>
<介绍></介绍>
</学生>
<学生 number="102">
<名字>白骨精</名字>
<年龄>140</年龄>
<介绍>幻化万千</介绍>
</学生>
<学生 number="103">
<名字>猪八戒</名字>
<名字>猪无能</名字>
<年龄>200</年龄>
<介绍>能吃会睡</介绍>
</学生>
</班级>
*/

class xmlDom{
    public $version;
    public $encoding;
    private $xml;
    private $items;
    private $seachNode = '';
    private $seachItem = '';
    private $seachValue = '';
    public $writeBytes = 0;

    function __construct($xmlFile ='', $version ='1.0', $encoding = 'UTF-8'){
        $this->version = $version;
        $this->encoding = $encoding;
        $this->xml = new DOMDocument($version, $encoding);
        if($xmlFile)$this->xml->load($xmlFile);
    }
    function getRootEle($rootTag){
        $this->xmlRoot = $this->xml->getElementsByTagName($rootTag)->item(0);
    }
    function getSeachItem($itemsTag, $seachNode, $seachValue){
        $this->items = $this->xml->getElementsByTagName($itemsTag);
        $this->items->length;
        for($i=0; $i<$this->items->length; $i++){
            $item = $this->items->item($i);//元素
            $node = $item->getElementsByTagName($seachNode);//节点
            for($j = 0; $j< $node->length; $j++){
                $subNode = $node->item($j);
                if($seachValue == $subNode->nodeValue){
                    $this->seachNode = $subNode;
                    $this->seachItem = $item;
                    $this->seachValue = $subNode->nodeValue;
                    break(2);
                }
            }
        }
        return ($this->seachNode) ? true : false;
    }
   
    function update($nodeValue, $nodeTag = '',$append = false, $index = 0){
        if($append){
            if($nodeTag)
                $this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue += $nodeValue;
            else
                $this->seachNode->nodeValue += $nodeValue;
        }else{
            if($nodeTag)
                $this->seachItem->getElementsByTagName($nodeTag)->item($index)->nodeValue = $nodeValue;
            else
                $this->seachNode->nodeValue = $nodeValue;
        }
    }
   
    function save($filename){
        $this->writeBytes = $this->xml->save($filename);
        return ($this->writeBytes) ? true : false;
    }
}

$test = new xmlDom('student.xml');
$test->getSeachItem('学生','年龄','103');//找到 年龄=103 的猪八戒
$test->update('小猪猪', '名字', false, 1); //把猪八戒的第二个名字改成:小猪猪
$test->save('new.xml'); //保存成新文件

上面是使用了dom来操作,下面我们利用php中的SimpleXML来操作xml,也算是很标准的一个操作xml文档的类了。

simplexml_load_file(string filename)
这里的 filename变量是用于存储 XML数据文件的文件名及其所在路径。以下代码使用 simplexml_load_file函数来创建了一个 SimpleXML对象。

 代码如下 复制代码

<?php
$xml = simplexml_load_file(’example.xml’); //创建 SimpleXML对象
print_r($xml);         //输出 XML
?>

其中,example.xml存储的数据与上面的$data完全相同,运行结果也与上面完全相同。
上面两种方法实现了同样的功能,其区别就在于 XML的数据源不同。如果 XML的数据源在 PHP脚本文件中,则需要使用 simplexml_load_string来进行创建。如果 XML的数据源在一个单独的 XML文件中,则需要使用 simplexml_load_file来进行创建。

读取 XML数据中的标签
与操作数组类型的变量类似,读取 XML也可以通过类似的方法来完成。例如,如果需要读取上面 XML数据中每一个“ depart”标签下的“name”属性,可以通过使用 foreach函数来完成,如以下代码
所示。

 代码如下 复制代码

<?php $xml = simplexml_load_file(’example.xml’); foreach($xml->depart as $a)
{
echo “$a->name <BR>”;
}
?>

运行结果如下所示。
production support
testing center
//读取 XML文件 //循环读取 XML数据中的每一个 depart标签
//输出其中的 name属性
也可以使用方括号“ []”来直接读取 XML数据中指定的标签。以下代码输出了上面 XML数据中的第一个“depart”标签的“name”属性。

 

 代码如下 复制代码
<?php
$xml = simplexml_load_file(’example.xml’); //读取 XML文件
echo $xml->depart->name[0]; //输出节点
?>

运行结果如下所示。
production support
对于一个标签下的所有子标签,SimpleXML组件提供了 children方法进行读取。例如,对于上面的 XML数据中的“ depart”标签,其下包括两个子标签:“ name”和“employees”。以下代码实现了对第一个“depart”标签下的子标签的读取。

DOMDocument这个功能是我们php中自带的一个功能,下面我来介绍利用DOMDocument生成xml文档,并且也介绍DOMDocument解析xml文件的方法,有需要的朋友可参考。

数组

 代码如下 复制代码

$arr[] = array(

'name' => $row['name'],

'sex' => $row['sex'],

'age' => $row['age']

);

生成php

 代码如下 复制代码

$doc = new DOMDocument('1.0', 'utf-8'); // 声明版本和编码

$doc->formatOutput = true;
$r = $doc->createElement("root");

$doc->appendChild($r);
foreach ($arr as $dat) {

$b = $doc->createElement("data");
$name = $doc->createElement("name");

$name->appendChild($doc->createTextNode($dat['name']));

$b->appendChild($name);
$sex = $doc->createElement("sex");

$sex->appendChild($doc->createTextNode($dat['sex']));

$b->appendChild($sex);

$age = $doc->createElement("age");

$age->appendChild($doc->createTextNode($dat['age']));

$b->appendChild($age);

$r->appendChild($b);

}
echo $doc->saveXML();

这样就生成了一个xml文件了

解析xml文件也是非常的简单了

 代码如下 复制代码

header("Content-type:text/html; Charset=utf-8");

$url = "createXML.php";

$reader = new XMLReader(); //实例化XMLReader

$reader->open($url); //获取xml

$i=1;

while ($reader->read()) {

if ($reader->nodeType == XMLReader::TEXT) { //判断node类型

$m = $i%3;

if($m==1)

$name = $reader->value; //读取node值

if($m==2)

$sex = $reader->value;

if($m==0){

$age = $reader->value;

$arr[] = array(

'name' => $name,

'sex' => $sex,

'age' => $age

);

}

$i++;

}

}

//print_r($arr);

本文章简单介绍关于php中DOMElement操作xml文档程序有需要的朋友可参考。

例1

 代码如下 复制代码

<?php

//Store your html into $html variable.

$html="<html>
<head>
<title>Rakesh Verma</title>
</head>

<body>
    <a href='http://example.com'>Example</a>
    <a href='http://google.com'>Google</a>
    <a href='http://www.yahoo.com'>Yahoo</a>
</body>

</html>";

$dom = new DOMDocument();
$dom->loadHTML($html);

//Evaluate Anchor tag in HTML
$xpath = new DOMXPath($dom);
$hrefs = $xpath->evaluate("/html/body//a");

for ($i = 0; $i < $hrefs->length; $i++) {
        $href = $hrefs->item($i);
        $url = $href->getAttribute('href');

        //remove and set target attribute       
        $href->removeAttribute('target');
        $href->setAttribute("target", "_blank");

        $newURL=$url.".au";

        //remove and set href attribute       
        $href->removeAttribute('href');
        $href->setAttribute("href", $newURL);
}

// save html
$html=$dom->saveHTML();

echo $html;

?>

例2

 代码如下 复制代码

/*<?xml version="1.0" encoding="UTF-8" standalone="no"?>
 <!-- css的样式定义,不加点。如:name{color:red;} -->
<?xml-stylesheet type="text/css" href="css.css"?>
<!-- 引入dtd文档定义文件 (根元素:班级)<!DOCTYPE 班级 SYSTEM "class.dtd" /> -->
<!-- <!DOCTYPE 班级[
<!ELEMENT 班级 (学生+)>
<!ELEMENT 学生 (名字,年龄,介绍)>
<!ELEMENT 名字 (#PCDATA)>
<!ELEMENT 年龄 (#PCDATA)>
<!ELEMENT 介绍 (#PCDATA)>
] /> -->
<班级>
<学生 number="101">
<名字>孙悟空</名字>
<名字>孙行者</名字>
<年龄>123</年龄>
<介绍><![CDATA[&*$%特殊字串^&#$&]]></介绍>
</学生>

<学生 number="10&quot;2">
<名字>白骨精</名字>
<年龄>140</年龄>
<介绍>介绍内容</介绍>
</学生>
</班级>
*/
$xmldoc = new DOMDocument('1.0', 'UTF-8');
$xmldoc->load('datas.xml');

$itemsNodeList = $xmldoc->getElementsbyTagName('学生');
$itemElement = $itemsNodeList->item(0);//得到第一个完整的学生信息节点
$itemChildsNodeList = $itemElement->getElementsbyTagName('名字');//得到子节点“名字”,也许有多个名字
$itemChildNode = $itemChildsNodeList->item(0);//得到第一个名字节点
echo $itemChildNode->nodeValue;//输出节点值

//封装成函数
$nodeArr = array('名字', '年龄', '介绍');
function getNodeVal($xmldoc, $itemsName, $nodeArr){
    $items = $xmldoc->getElementsByTagName($itemsName);
     for($i=0; $i < $items->length; $i++){
        $item = $items->item($i);
        foreach($nodeArr as $node){
            $data[$i][] = $item->getElementsByTagName($node)->item(0)->nodeValue;
        }
    }
    return $data;
}

$data = getNodeVal($xmldoc, '学生', $nodeArr);
print_r($data);

[!--infotagslink--]

相关文章