DOMXML函数笔记

2019-04-07 19:26:14刘景俊

// 节点的遍历
/**
  节点结构
  DomElement Object
    type = 1
    tagname = 节点名
  DomText Object
    type = 3
    content = 节内容点
  DomCData Object
    type = 4
    content = 节内容点

  DomProcessingInstruction Object
    type 无
    target = 处理指令
    data = 参数

*/
$ar[] = $doc->root();  // 取得根节点
$ar[] = $ar[count($ar)-1]->children();
$ar[] = $ar[count($ar)-1][0]->children();

// 函数domxml_children() 不能返回节点参数
// 返回节点参数需要使用domxml_attributes()
//var_dump(domxml_attributes($head));
//print_r($ar[1][0]->attributes());
//print_r($ar);

function xml_dumpmem($xmldoc) {
  static $mode = 0;
  $xmlstr = "";
  // 获取节点,保存在数组中
  if(get_class($xmldoc) == "DomDocument") {
    $xmlstr = '<?xml version="1.0" encoding="gb2312"?>'."n";
    if(count($xmldoc->children) == 1)  // 根节点,没有其他成员
      $docs[] = $xmldoc->root();
    else
      $docs = $xmldoc->children();  // 根节点,有其他成员
  }else {
    $docs = $xmldoc->children();  // 一般节点
  }

//  echo __LINE__."<br>";
  foreach($docs as $doc) {
    $attr = $doc->attributes();
    switch($doc->type) {
      case 1:
        $xmlstr .= "<{$doc->tagname}";  // 标签头
        if($attr) {
          foreach($attr as $key)
            $xmlstr .= " {$key->name}="{$key->value}"";  // 标签参数
        }
        $xmlstr .= ">";  // 标签结束
        $xmlstr .= xml_dumpmem($doc);  // 进入子节点
        $xmlstr .= "</{$doc->tagname}>";  // 闭合标签
        break;
      case 3:
        $xmlstr .= $doc->content;
        break;
      case 4:
        $xmlstr .= "<![CDATA][";
相关文章 大家在看