php xml解析类

 更新时间:2016年11月25日 16:55  点击:1253

 <?php
/*Khalid XML files parser :: class kxparse, Started in March 2002 by Khalid Al-kary*/
class kxparse{
var $xml;
var $cursor;
var $cursor2;

//the constructor $xmlfile is the file you want to load into the parser
function kxparse($xmlfile)
{
 //just read the file
 $file=fopen($xmlfile,"r");
 
 //put the text inside the file in the XML object variable
 while (!feof($file))
  {
   $this->xml.=fread($file,4096);  
  }
 
 //close the opened file
 fclose($file);

 //set the cursor to 0 (start of document), the cursor is later used by another functions
 $this->cursor=0;

 //set the second curosr to the end of document
 $this->cursor2=strlen($this->xml);
}

/*this function first gets a copy of the XML file starting from cursor and ending with cursor2
and then counts the number of occurences of the given tag name inside that area
returns an array (occurrence index -> occurence position in the XML file)
this function is half of the engine that moves Kxparse */
function track_tag_cursors($tname)
 {
  //getting the copy as intended
  $currxml=substr($this->xml,$this->cursor,$this->cursor2);
  
  //counting the number of occurences in the cut area
  $occurs=substr_count($currxml,"<".$tname);
  
  //the aray that will be returned
  $tag_poses=array();
  
  //setting its 0 to 0 because indeces in Kxparse start from 1
  $tag_poses[0]=0;
  
  //for each of the occurences
  for ($i=1;$i<=$occurs;$i++)
   {
    
    if ($i!=1)
     {
      //if it's not the first occurence
      //start checking for the next occurence but first cut the previous occurences off from the string
      $tag_poses[$i]=strpos($currxml,"<".$tname,$tag_poses[$i-1]+1-$this->cursor)+$this->cursor;
     }
    else
     {
      //if its the first occurence just assign its value + the cursor (because the position is in the XML file wholly
      $tag_poses[$i]=strpos($currxml,"<".$tname)+$this->cursor;
     }
     
   }
  
  //return that array 
  return $tag_poses;
 }
//this function strips and decodes the tag text...
function get_tag_text_internal($tname)
 {
  //strip the tags from the returned text and the decode it
  return $this->htmldecode(strip_tags($tname));
 }

//function that returns a particular attribute value ...
//tag is the tag itself(with its start and end)
function get_attribute_internal($tag,$attr)
 {
  //identifying the character directly after the tag name to cut it then
  if (strpos($tag," ")<strpos($tag,">"))
   {
    $separ=" ";
   }
  else
   {
    $separ=">";
   }

  //cutting of the tag name according to separ
  $tname=substr($tag,1,strpos($tag,$separ)-1);

  //cut the tag starting from the white space after the tag name, ending with(not containing) the > of the tag start
  $work=substr($tag,strlen($tname)+1,strpos($tag,">")-strlen($tname)-1);

  //get the index of the tag occurence inside $work
  $index_of_attr=strpos($work," ".$attr."="")+1;

  //check if the attribute was found in the tag
  if ($index_of_attr)
   {
    //now get the attributename+"=""+attrbutevalue+""" and extract the value from between them
    //calculate from where we will cut
    $index_of_value=$index_of_attr+strlen($attr)+2;

    //cut note the last argument for calculating the end
    $work=substr($work,$index_of_value,strpos($work,""",$index_of_value)-$index_of_value);

    //now return the attribute value
    return $work;
   }

   //if the attribute wasn't found, return false'
  else
   {
    return FALSE;
   }
 }


//this function HTML-decodes the var $text...
function htmldecode($text)
 {
  $text=str_replace("&lt;","<",$text);
  $text=str_replace("&gt;",">",$text);
  $text=str_replace("&amp;","&",$text);
  $text=str_replace("&ltt;","&lt;",$text);
  $text=str_replace("&gtt;","&gt;",$text);
  return $text;
 }

//the function that saves a file to a particular location
function save($file)
 {
  //open the file and overwrite of already avilable
  $my_file=fopen($file,"wb");

  //$my_status holds wether the operation is okay
  $my_status=fwrite($my_file,$this->xml);

  //close the file handle
  fclose($my_file);

  if ($my_status!=-1)
   {
    return TRUE;
   }
  else
   {
    return FALSE;
   }

 }

//function that gets a tag in the XML tree (with its starting and ending)
function get_tag_in_tree($tname,$tindex)
 {
  $this->get_work_space($tname,$tindex);
  return substr($this->xml,$this->cursor,$this->cursor2-$this->cursor);
 }
//function that gets the text of a tag
function get_tag_text($tname,$tindex)
{
 $mytag=$this->get_tag_in_tree($tname,$tindex);
 return $this->get_tag_text_internal($mytag);

//funtion that counts the number of occurences of a tag in the XML tree 
function count_tag($tname,$tindex)
 {
  return $this->get_work_space($tname,$tindex);
 }
 
//functoin that gets the attribute value in a tag 
function get_attribute($tname,$tindex,$attrname) 
 {
  $mytag=$this->get_tag_in_tree($tname,$tindex);
  return $this->get_attribute_internal($mytag,$attrname);
 }

//Very important function, half of the engine
//sets the $this->cursor and $this->cursor2 to the place where it's intended to work 
function get_work_space($tname,$tindex) 
 {
  //counts the number of ":"  in the given colonedtagindex
  $num_of_search=substr_count($tindex,":");
  
  //counts the number of ":" in the given colonedtagname
  $num_of_search_text=substr_count($tname,":");
  
  //checks if they are not equal this regarded an error
  if ($num_of_search!=$num_of_search_text)
   {
    return false;
   }
  else
   {
    //now get the numbers in an array
    $search_array=explode(":",$tindex);
    
    //and also get the corresponding tag names
    $search_text_array=explode(":",$tname);
    
    //set the cursor to 0 in order to erase former work
    $this->cursor=0;
    
    //set the cursor2 to the end of the file for the same reason
    $this->cursor2=strlen($this->xml);
    
    //get the first tag name to intiate the loop
    $currtname=$search_text_array[0];
    
    //get the first tag index to intiate the loop
    $currtindex=$search_array[0];
    
    //the loop according to number of ":"
    for ($i=0;$i<count($search_array);$i++)
     {
      //if it's not the first tag name and index
      if ($i!=0)
       {
        //so append the latest colonedtagname to the current tag name
        $currtname=$currtname.":".$search_text_array[$i];
        
        //and append the latset colonedtagindex to the current tag index
        $currtindex=$currtindex.":".$search_array[$i];
       }
      //$arr holds the number of occurences of the current tag name between the cursor and cursor2 
      $arr=$this->track_tag_cursors($search_text_array[$i]);
      
      //the index which you want to get the position of
      $tem=$search_array[$i];
      
      //to support count_tag_in_tree
      //when given a ? it returns the number of occurences of the current tag name
      if ($tem=="?")
       {
        return count($arr)-1;
       }
      else { 
      
      //to support the auto-last method
      //if the current tag index equals "-1" so replace it by the last occurence index
      if ($tem==-1) 
       {
        $tem=count($arr)-1;
       }
      
      //now just set cursor one to the occurence position in the XML file accrding to $tem 
      $this->cursor=$arr[(int)$tem];
      
      //and set cursor2 at the end of that tag
      $this->cursor2=strpos($this->xml,"</".$search_text_array[$i].">",$this->cursor)+strlen("</".$search_text_array[$i].">");
       }
     }
   } 
}
//the function that appends a tag to the XML tree
function create_tag($tname,$tindex,$ntname) 
 {
  //first get the intended father tag
  $this->get_work_space($tname,$tindex);
  
  //explode the given colonedtagname into an array
  $search_text_array=explode(":",$tname);
  
  //after setting the cursors using get_work_space
  //get a cope of the returned tag
  $workarea=substr($this->xml,$this->cursor,$this->cursor2-$this->cursor);
  
  //calculate the place where you will put the tag start and end
  $inde=$this->cursor+strpos($workarea,"</".$search_text_array[count($search_text_array)-1].">");
  
  //here, replace means insert because the length argument is set to 0
  $this->xml=substr_replace($this->xml,"<".$ntname."></".$ntname.">",$inde,0);
 }
//the function that sets the value of an attribute 
function set_attribute($tname,$tindex,$attr,$value)
 {
  //first set the cursors using get_work_space
  $this->get_work_space($tname,$tindex);
  
  //now get a copy of the XML tag between cursor and cursor2
  $currxml=substr($this->xml,$this->cursor,$this->cursor2-$this->cursor);
  
  //cut the area of the tag on which you want to work
  //starting from the tag "<" and ending with the opening tag ">"
  $work=substr($currxml,0,strpos($currxml,">")+1);
  
  //if the attribute is already available
  if (strpos($work," ".$attr."=""))
  {
   //calculate the current value's length
   $currval_length=strlen($this->get_attribute_internal($currxml,$attr));
   
   //get the position of the attribute inside the tag
   $my_attribute_pos=strpos($work," ".$attr."="")+1;
   
   //get the length of the attribute
   $my_attribute_length=strlen($attr);
   
   //now replace the old value
   $this->xml=substr_replace($this->xml,$value,$this->cursor+$my_attribute_pos+$my_attribute_length+2,$currval_length);
   return TRUE;
  }
  
  //if the attribute wasn't already available'
  else
  {
   //check if there are other attributes in the tag
   if (strpos($work," "))
    {
     $separ=" ";
    }
   else
    {
     $separ=">";
    }
   
   //prepare the attribute
   $newattr=" ".$attr."="".$value.""";
   
   //insert the new attribute
   $this->xml=substr_replace($this->xml,$newattr,$this->cursor+strpos($work,$separ),0);
   return TRUE;
  } 
}
//the function that changes or adds the text of a tag
function set_tag_text($tname,$tindex,$text)
 {
  //firs get set the cursors using get_work_space
  $this->get_work_space($tname,$tindex);
  
  //explode the given colonedtagname in an array
  $search_text_array=explode(":",$tname);
  
  //get the latest name
  $currtname=$search_text_array[count($search_text_array)-1];
  
  //calculate the start of replacement
  $replace_start_index=strpos($this->xml,">",$this->cursor)+1;
  
  //calculate the end of replacement
  $replace_end_index=strpos($this->xml,"</".$currtname.">",$this->cursor)-1;
  
  //calculate the length between them
  $tem=$replace_end_index-$replace_start_index+1;
  
  //and now replace
  $this->xml=substr_replace($this->xml,$text,$replace_start_index,$tem);
 }
//functio that removes a tag 
function remove_tag($tname,$tindex) 
 {
  //set the cursors using get_work_space
  $this->get_work_space($tname,$tindex);
  
  //now replace with ""
  $this->xml=substr_replace($this->xml,"",$this->cursor,$this->cursor2-$this->cursor);
 }

}
?>                                                                                                                              testing.xml                                                                                         0100400 0177776 0177776 00000001125 07561460576 013104  0                                                                                                    ustar   nobody                          nogroup                                                                                                                                                                                                                <?xml version="1.0"?>
<tryingxml testattribute="we are here">
<firstlevel testingattribute="no we aren't here">
sometext for the first level
<secondlevel testingattribute="We are there">
some text for the second level
<thirdlevel testingattribute="we aren't there">
some text for the third level
</thirdlevel>
<thirdlevel testingattribute="we are every where :)">
this is a test of multiple children per parent node
<justachild testingattribute="a value ofcourse">is it okay with you now ? go check the script</justachild>
</thirdlevel>
</secondlevel>
</firstlevel>
</tryingxml>
                                                                                                                                                                                                                                                                                                                                                                                                                                           nav.php                                                                                             0100400 0177776 0177776 00000000543 07561460576 012205  0                                                                                                    ustar   nobody                          nogroup                                                                                                                                                                                                                <?php
//including khalid xml parser
include_once "kxparse.php";

//create the object
$xmlnav=new kxparse("nav.xml");

for ($i=1;$i<=$xmlnav->count_tag("nav:item","1:?");$i++)
{?>
<div class="navit"><a href="<?php echo $xmlnav->get_attribute("nav:item","1:".$i,"href") ?>"><?php echo $xmlnav->get_tag_text("nav:item","1:".$i) ?></a></div>
<?}?>
                                                                                                                                                             nav.xml                                                                                             0100400 0177776 0177776 00000000507 07561460576 012216  0                                                                                                    ustar   nobody                          nogroup                                                                                                                                                                                                                <?xml version="1.0"?>
<nav>
<item href="http://111cn.net/kxparse/index.php">Home</item>
<item href="http://111cn.net/kxparse/news.php">News</item>
<item href="http://111cn.net/kxparse/docs.php">Documentation</item>
<item href="http://111cn.net/kxparse/changelog.php">Change Log</item>
</nav>

<?
class arrayTree
{
 private $stack;
 private $tree;
 private $location;
 private $locationstring;
 
 
 public function __construct($tree = false)
 { $this->stack = array();
  if ($tree)
   $this->tree = $tree;
  else
   $this->tree = array();
   
  $this->location = 0;
 }
 
 public  function startBranch()
 { $this->location++;
  $this->stack[] = $this->location;
  $this->location = 0;
  $this->nodes = 0;
  $this->locationstring = "";
  foreach($this->stack as $v)
   $this->locationstring .="['node:$v']";

  eval('$this->tree'."$this->locationstring = array(); ");
  eval('$this->tree'."$this->locationstring"."['nodes'] = 0; ");

 }
 public  function addLeaf($name, $value)
 { $name = htmlspecialchars($name, ENT_QUOTES); 
  if (is_array($value) && sizeof($value)> 0)   
  { $arr = "array( ";
   foreach($value as $n=>$v)
   { $v = addslashes("$v");
    $arr .= "'$n' => '$v',";
   }
   $arr .= "'$n' => '$v')";
   //echo '$this->tree'."$this->locationstring"."['$name']"." = $arr; ";
   eval ('$this->tree'."$this->locationstring"."['$name']"." = $arr; ");

  }
  else
  {
   if (is_array($value) && sizeof($value)== 0)
    $value = '';
 
   $value = htmlspecialchars($value, ENT_QUOTES);
   $tmp = '$this->tree'."$this->locationstring"."['$name']".' = "$value";'." ";
   //echo ($tmp);
   eval($tmp);
  }  
 }
 public  function endBranch()
 { 
  $this->location = array_pop($this->stack);
  $this->locationstring = "";
  foreach($this->stack as $v)
   $this->locationstring .= "['node:$v']";

  eval('$this->tree'."$this->locationstring"."['nodes'] = $this->location; ");   
 }
 public function gettree()
 { return $this->tree;
 }
}


/***************************************************
**  XMLParser Object
**  Helper object for parsing XML into an arrayTree
***************************************************/
 
class XMLParser

 private $filename;
 private $data;
 private $currentItem;
 private $didread;
 private $depth;
 private $deptharr;
 private $parsed;
 private $pointer;
 private $parser;
 private $p;
 private $arrayout;
 private $tree;
 
 
 public  function __construct($xml, $isfile = true)
 { 
  if ($isfile)
  { $file = $xml;
   $this->filename = $file;
  }
  else
  { $this->data = $xml;
   $this->filename = false;
  }
   
  $this->tree = new arrayTree;
  $this->tree->addLeaf('nodes', 0);
    $this->depth = 0;
  $this->deptharr = array();
  $this->pointer = '$this->parsed';
  $this->currentItem = array();
  $this->didread = false; 
  $this->parsed = array();
  $this->arrayout = "";
 }  
 
 public  function startElement($parser, $name, $attrs)
 { $this->parsed = "";
  $this->tree->startBranch();
  $this->tree->addLeaf('name', $name);
  $this->tree->addLeaf('attributes', $attrs);
 }
 public  function characterData($parser, $data)
 { if (!$this->didread)
   $this->parsed  = $data;
  else
   $this->parsed .= $data;
  $this->didread = true;
 }
 public function endElement($parser, $name)
 { $this->tree->addLeaf('value',$this->parsed);
  $this->parsed = "";
  $this->tree->endBranch(); 
 }
 public function parse()
 { 
  
  $this->parser = xml_parser_create();
  xml_set_object($this->parser, $this);
  xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, false);
  xml_set_element_handler($this->parser, "startElement", "endElement");
  xml_set_character_data_handler($this->parser, "characterData");
  
  if ($this->filename !== false)
  { $data = file_get_contents($this->filename);
   if (!$data)
    return false;
  }
  else
   $data = $this->data;

     $data=eregi_replace(">"."[[:space:]]+"."<","><",$data);
       $data=str_replace("&","&amp;",$data);
     if (!xml_parse($this->parser, $data))
     {   die(sprintf("XML error: %s at line %d",
            xml_error_string(xml_get_error_code($this->parser)),
               xml_get_current_line_number($this->parser)));
     }
  xml_parser_free($this->parser);
  $data=str_replace("&amp;","&",$this->tree->gettree());
  return $data['node:1'];
 }
 
 
}


/***************************************************
**  swiftXML Object
**  Allows user access to XML data stored in tree
***************************************************/

class swiftXML implements IteratorAggregate
{
 private $XMLtree;
 
 public function __construct(&$xml = false, $type = XML_FILE)
 {
  if (is_array($xml) || $type == XML_TREE)
  {  $this->usearray($xml);
  }
  else if ($type == XML_FILE)
  { $this->usefile($xml);
   
  }
  else if ($type == XML_TEXT)
  { $this->usetext($xml);
  }
  
 }

 public function & __get($x)
 {
  return $this->get($x); 
 }
 
 public function __set($x,$y)
 { 
  $this->set($x,$y);

 }
 public function __call($x, $y)
 { if (array_key_exists($x,$this->XMLtree))
   return $this->XMLtree[$x];
  else
   return false;
 }
 
 public function __toString()
 {
  return $this->XMLtree['value'];
 }
 // Iterator function
 public function getIterator()
 {   return new ArrayIterator($this->XMLtree);
    }
 
 // initialize functions
 public function usefile($file)
 { $x = new XMLParser($file);
  $this->XMLtree = $x->parse();
 }

 public function usetext($text)
 { $x = new XMLParser($text,false);
  $this->XMLtree = $x->parse();
 }
 public function usearray(&$arr)
 { $this->XMLtree = $arr;
 }
 
 
 // return Tree as XML
 public function asXML($header = true, $tree = false, $depth = 0)
 { if (!$tree)
   $tree = $this->XMLtree;
  $output = "";
  if ($header)
  { 
   $output = "<?xml version="1.0" encoding="UTF-8" ?> ";
  }
 
  $tabs = str_repeat (" ",$depth);
  $output .= "$tabs<$tree[name]";
  if ($tree['attributes'] != "" && is_array($tree['attributes']))
  { foreach ($tree['attributes'] as $n => $v)
     $output .= " $n="$v"";
  }
  $output .= ">$tree[value]";
  
  if ($tree['nodes'] > 0)
  { foreach ($tree as $n => $v)
   { if (substr($n,0,5) == "node:")
     $output .= " " . $this->asXML(false,$tree[$n],$depth+1);
   } 
   $output .=" $tabs"; 
  
  }
  $output .="</$tree[name]>";
  return $output;
 }
 
 // return XMLtree
 public function getDetailedTree()
 { return $this->XMLtree;
 }
 
 // return a simplified tree as an array, where the array keys correspond to XML tags
 public function getSimpleTree($showattribs = false, &$tree = false)
 { if (!$tree)
   $tree = $this->XMLtree;
  // tree has no branches
  if (sizeof($tree) < 5)
   return $tree['value'];
 
  $output = array();
  foreach($tree as $n=>$v)
  {  if(substr($n,0,5) == 'node:')
   { $vname = $v['name'];
    $attribstr = "";
    $vattrib = $v['attributes'];
    if (array_key_exists($vname, $output))
    { if (!is_array($output[$vname]) || !array_key_exists(0,$output[$vname]))
     { $existingvalue = $output[$vname];
      $existingvattrib = false;
      if ($showattribs && array_key_exists($vname."/attributes",$output))
       $existingvattrib = $output[$vname."/attributes"];
      $output = array();
      $output[$vname] = array();     
      $output[$vname][] = $existingvalue;
     
      if ($showattribs  && $existingvattrib)
       $output[$vname]["0/attributes"] = $existingvattrib;
     }
     $output[$vname][] = $this->getSimpleTree($showattribs,$v);
     if ($showattribs && is_array($vattrib))
      $output[$vname][end(array_keys($output[$vname]))."/attributes"] = $vattrib;
    }
    else
    { 
     $output[$vname] = $this->getSimpleTree($showattribs, $v);  
     //echo "-->$vname:".$output[$vname]." ";
     if ($showattribs && is_array($vattrib))
      $output[$vname."/attributes"]= $vattrib;
    }
   }
  }
  return $output;
 } 

 // $location takes the format "block1/block2/block3"
 private function & getNodeByLocation($location, &$tree= false)
 { if (!$tree)
   $tree = &$this->XMLtree;

   
  
  $location = ereg_replace("^/", "",$location);
  $location = ereg_replace("/$", "",$location);


  if ($slashpos = strpos($location,"/"))
  { $nodename = substr($location,0,$slashpos);
   $rest = substr($location,$slashpos+1,strlen($location)-$slashpos+1);
   return $this->getNodeByLocation($rest,$this->getNodebyName($tree, $nodename));
  }
  else
   return $this->getNodeByName($tree, $location);
 }
 
 public function doesExist($location)
 { return getNodeByLocation($location) ==! false ? true : false;
 }
 
 // returns XML object
 public function & getNode($location)
 { $tmp = $this->getNodeByLocation($location);
  if ($tmp === false)
   return false;
  else
   return new swiftXML($tmp,XML_TREE);
 }
 
 // accepts $newnode as XML object
 public function setNode($newnode, $location)
 { $locnode = &$this->getNodeByLocation($location);
  //print_r($locnode);
  
  $locnode = $newnode->getDetailedTree();
 }
 public function getValue($location)
 { 
  $arr = $this->getNodeByLocation($location);
  if ($arr !== false)
   return $arr['value'];
  else
   return false;
 }
 
 public function setValue($value, $location = false)
 { 
  if (!$location)
   $arr = &$this->XMLtree;
  else
   $arr = &$this->getNodeByLocation($location);
  
  $arr['value'] = $value;
  

 }
 public function set($location,$value)
 {
  
  if (is_array($value))
   $this->setTree($value,$location);
  else if (is_a($value, "swiftXML"))
   $this->setNode($value,$location);
  else
   $this->setValue($value,$location);
   
 }
 
 public function setTree($value, $location= false)
 { if (!$location)
   $arr = &$this->XMLtree;
  else 
   $arr = &$this->getNodeByLocation($location);
   
  
  $arr = $value;
 }
 
 public function getAttributes($location)
 { 
  $arr = $this->getNodeByLocation($location);
  return $arr['attributes'];
 }
 
 public function getAttribute($location, $attrib)
 { 
  $arr = $this->getNodeByLocation($location);
  if (array_key_exists($attrib, $arr['attributes']))
   return $arr['attributes'][$attrib];
  else
   return false;
 }
 
 public function setAttribute($attribname, $attribvalue, $location = false)
 { if (!$location)
   $arr = &$this->XMLtree;
  else
   $arr = &$this->getNodeByLocation($location);

  if (!is_array($arr['attributes']))
   $arr['attributes'] = array();
   
  $arr['attributes'][$attribname] = $attribvalue;
 }
 
 public function setAttributes($arr, $location = false)
 { if (!$location)
   $arr2 = &$this->XMLtree;
  else
   $arr2 = &$this->getNodeByLocation($location);

  $arr2['attributes'] = $arr;
  
 }
 
 // Easiest way to get info from an XML document is to use function get()
 // get() guesses what format you'd like the data in based on the data. 
 // It will return an array of XML objects if $location is ambiguous. 
 // If one tag exists at $location, it will be returned and an XML object, unless it has no attributes,
 // in which case the value be returned as a string.
 //
 // Use the prefix // to indicate a location wildcard (run getNodeArrayRecursize)
 public function get($location)
 { 
  if (ereg("^//",$location) || ereg("^*/",$location))
   return $this->getNodeArrayRecursive(substr($location,2,strlen($location)-2));
 
   
  $output = $this->getNodeArray($location);
  
  
  if ($output !== false && count($output) == 1)
  { $tree = $output[0]->getDetailedTree();
   if ($tree['nodes'] == 0 && !is_array($tree['attributes']))
    $output = $tree['value'];
   else
    $output = $output[0];
  }
  return $output;   
 }
 
 public function getNodeArray($location)
 { 
     if (ereg("^//",$location) || ereg("^*/",$location))
   return $this->getNodeArrayRecursive(substr($location,2,strlen($location)-2));
  
  $output = array();
  $lastpos = strrpos($location, "/");
  if ($lastpos !== false)
  { $subloc = substr($location,0,$lastpos);
   $nodename = substr($location,$lastpos+1,strlen($location)-1); 
   $node = $this->getNode($subloc);

   if ($node === false)
    return false;
    
   $tree = $node->getDetailedTree();
  
  }
  else
  { $subloc = $location;
   $nodename = $location;
   $tree = $this->XMLtree;
  }
    
  for ($i = 1; $i <= $tree['nodes']; $i++)
  { if ($tree["node:$i"]['name'] == $nodename)
    $output[] = swiftXML_use_tree($tree["node:$i"]);
  }
  if (count($output) == 0)
   return false;
  else
   return $output;
  
 }
 
 // returns an array of any node named $location in $tree
 private function getNodeArrayRecursive($location, $tree = false)
 { if (!$tree)
   $tree = $this->XMLtree;
   
  $output = array();
  if ($tree['name'] == $location)
   $output[] = swiftXML_use_tree($tree);
  
  for ($i = 1; $i <= $tree['nodes']; $i++)
   $output =array_merge($output, $this->getNodeArrayRecursive($location,$tree["node:$i"]));
  
  return $output; 
 }
 
 // assistant function; pulls a Subarray from the $tree
 private  function & getNodeByName(&$tree, $name, $debug = false)
 { if ($debug) echo "getNodeByName($tree,$name); ";
  if (!is_array($tree))
  { if ($debug) echo ("[".$tree."]");
   return false;
  }
  
  foreach ($tree as $n => $v)
  { if (is_array($v) and array_key_exists('name',$v))
   { if ($debug) echo $tree[$n]['name'] ." == $name ? ";
    if ($v['name'] == $name)
     return $tree[$n];    
   }
   if ($debug) echo $n." ";
  }
  return false;
 }
 
 
 public function createChild($name, $value = "", $attributes = "")
 { 
  $nodes = ++$this->XMLtree['nodes'];
  if (is_a($name, "swiftXML"))
  { $this->XMLtree["node:$nodes"] = $name->getDetailedTree();
   $nodes = $this->XMLtree['nodes'];
  }
  else
   $this->XMLtree["node:$nodes"] = array( "name" => $name,
             "value" => $value,
             "attributes" => $attributes,
             "nodes" => 0);
  return $nodes;
 } 
 
}

define("XML_FILE","file");
define("XML_TREE","tree");
define("XML_TEXT","text");
define("XML_NO_CURL",false);
 
// assistant functions for initializing XML objects
function & swiftXML_use_file($filename, $use_curl = true)

 if (ereg("://",$filename) && $use_curl && function_exists('curl_init'))
  return swiftXML_use_curl($filename);
 else
  return new swiftXML($filename, XML_FILE);
}

function & swiftXML_use_text($text)
{ return new swiftXML($text, XML_TEXT);
}


function & swiftXML_use_tree($tree)
{ return new swiftXML($tree, XML_TREE);
}

function & swiftXML_use_curl($filename)
{
 $ch = curl_init();

 curl_setopt($ch, CURLOPT_URL, $filename);
 curl_setopt($ch, CURLOPT_USERAGENT, "swiftXML/1.1");
 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
 curl_setopt($ch, CURLOPT_HEADER, 0);
 
 $text = curl_exec($ch);
 
 curl_close($ch);
 
 return new swiftXML($text, XML_TEXT);
}

function & swiftXML_create($name, $value = "", $attributes = "")
{
 return swiftXML_use_tree(array( "name" => $name,
         "value" => $value,
         "attributes" => $attributes,
           "nodes" => 0));
 

}
?>
分析xml文档
<html>
<body>
<?
include_once('swiftxml.1.1.php教程');

$XML= swiftXML_use_file('http://www.111cn.net教程/feed/rss2/');


echo "<h1>".$XML->get("/channel/title")."</h1>";
echo "<h2>".$XML->get("/channel/description")."</h2>";

foreach ($XML->get("//item") as $item)
{ $url   = $item->get("link");
 $title = $item->get("title");
 $desc  = $item->get("description");

 echo html_entity_decode("<h3><a href="$url">$title</a></h3><p>$desc</p> ");

}

?>
</body>
</html>

下创建 xml 文档
<?
include_once('swiftxml.1.1.php');

$rss = swiftXML_create("rss");
$rss->setAttribute("version", "2.0");

$channel = swiftXML_create("channel");
$channel->createChild("title","Swiftly Tilting");
$channel->createChild("link","http://www.111cn.net");

for($i = 0; $i < 10; $i++)
{ $item = swiftXML_create("item");
 $item->createChild("title","title $i");
 $item->createChild("description","description $i");
 $channel->createChild($item);
}

$rss->createChild($channel);

header("Content-type: text/xml");
echo $rss->asXML();

?>

 

接收xml:
$xml = file_get_contents('php://input');
 
发送(post):
$xml_data = <xml>...</xml>";
$url = http://dest_url
;
$header[] = "Content-type: text/xml";//定义content-type为xml
curl_setopt($ch, CURLOPT_URL, $url
);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
curl_setopt($ch, CURLOPT_POST, 1
);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data
);
$response = curl_exec($ch
);
if(
curl_errno($ch
))
{
    print
curl_error($ch
);
}
curl_close($ch);
 
或者:
$fp = fsockopen($server, 80);
fputs($fp, "POST $path HTTP/1.0rn");
fputs($fp, "Host: $serverrn");
fputs($fp, "Content-Type: text/xmlrn");
fputs($fp, "Content-Length: $contentLengthrn");
fputs($fp, "Connection: closern");
fputs($fp, "rn"); // all headers sent
fputs($fp, $xml_data);
$result = '';
while (!feof($fp)) {
$result .= fgets($fp, 128);
}
return $result;

php xml生成函数程序代码


function xml_file($filename, $keyid = 'errorentry')
{
   $string = implode('', file($filename));
   return xml_str($string, $keyid);
}

function xml_str($string, $keyid = 'errorentry')
{
 $parser = xml_parser_create();
 xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
 xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
 xml_parse_into_struct($parser, $string, $values, $tags);
 xml_parser_free($parser);
 $tdb = array();
 foreach ($tags as $key=>$val)
 {
  if($key != $keyid) continue;
  $molranges = $val;
  for ($i=0; $i < count($molranges); $i+=2)
  {
     $offset = $molranges[$i] + 1;
     $len = $molranges[$i + 1] - $offset;
     $tdb[] = xml_arr(array_slice($values, $offset, $len));
  }
 }
 return $tdb;
}

function xml_arr($mvalues)
{
 $arr = array();
 for($i=0; $i < count($mvalues); $i++)
 {
    $arr[$mvalues[$i]['tag']] = $mvalues[$i]['value'];
 }
 return $arr;
}

在很多应用中我们都会用到xml 特别是互动设计的朋友哦flash+xml等,下在我们就来一个实时的php输出xml 文件并进行分页吧。

<?php
    require_once("Inc/Conn.php");//系统配置文件
 $sql = "select *  from ose";
 $result = mysql_query($sql) ;
 $total = mysql_num_rows($result);
 if( $total )
 {
  $pagesize =4;
  $pagecount=($total % $pagesize)?(int)($total / $pagesize)+1:$total/$pagesize;//统计总页面
  $page  =isset($_GET['page'])?$_GET['page']:1;//取得当前页面
  $start =($page>=1 && $page<=$pagecount)?$start=$pagesize*($page-1):$start=1;//取得超始记录
  $sql.="  order by id desc limit $start,$pagesize" ;  
  $result = mysql_query( $sql );
  while( $rs = mysql_fetch_array($result) )
  {   
   $temp .= "<member id="".$rs['id']."" roomname="".$rs['User_Name'].""/>n";   
  }
 }
 else
 {
  die('{result:"false"}');
 }
 //die('bb');
 echo "<?xml version="1.0" encoding="gb2312" ?>n<root>n<page now="$page" count="$pagecount"/>n<roomlist>n",$temp,"</roomlist>n</root>";
 
?>

输出结果为:

[!--infotagslink--]

相关文章

  • php svn操作类

    以前我们开发大型项目时都会用到svn来同步,因为开发产品的人过多,所以我们会利用软件来管理,今天发有一居然可以利用php来管理svn哦,好了看看吧。 代码如下 ...2016-11-25
  • PHP 数据库缓存Memcache操作类

    操作类就是把一些常用的一系列的数据库或相关操作写在一个类中,这样调用时我们只要调用类文件,如果要执行相关操作就直接调用类文件中的方法函数就可以实现了,下面整理了...2016-11-25
  • 源码分析系列之json_encode()如何转化一个对象

    这篇文章主要介绍了源码分析系列之json_encode()如何转化一个对象,对json_encode()感兴趣的同学,可以参考下...2021-04-22
  • php中去除文字内容中所有html代码

    PHP去除html、css样式、js格式的方法很多,但发现,它们基本都有一个弊端:空格往往清除不了 经过不断的研究,最终找到了一个理想的去除html包括空格css样式、js 的PHP函数。...2013-08-02
  • JavaScript预解析,对象详解

    这篇文章主要介绍了JavaScript预解析,对象的的相关资料,小编觉得这篇文章写的还不错,需要的朋友可以参考下,希望能够给你带来帮助...2021-11-10
  • php常量详细解析

    一、常量常量是一个简单值的标识符(名字)。如同其名称所暗示的,在脚本执行期间该值不能改变(除了所谓的魔术常量,它们其实不是常量)。常量默认为大小写敏感。按照惯例常量标识符总是大写的。 常量名和其它任何 PHP 标签遵循...2015-10-30
  • JS+CSS实现分类动态选择及移动功能效果代码

    本文实例讲述了JS+CSS实现分类动态选择及移动功能效果代码。分享给大家供大家参考,具体如下:这是一个类似选项卡功能的选择插件,与普通的TAb区别是加入了动画效果,多用于商品类网站,用作商品分类功能,不过其它网站也可以用,...2015-10-21
  • Php文件上传类class.upload.php用法示例

    本文章来人大家介绍一个php文件上传类的使用方法,期望此实例对各位php入门者会有不小帮助哦。 简介 Class.upload.php是用于管理上传文件的php文件上传类, 它可以帮...2016-11-25
  • index.php怎么打开?如何打开index.php?

    index.php怎么打开?初学者可能不知道如何打开index.php,不会的同学可以参考一下本篇教程 打开编辑:右键->打开方式->经文本方式打开打开运行:首先你要有个支持运行PH...2017-07-06
  • PHP实现无限级分类(不使用递归)

    无限级分类在开发中经常使用,例如:部门结构、文章分类。无限级分类的难点在于“输出”和“查询”,例如 将文章分类输出为<ul>列表形式; 查找分类A下面所有分类包含的文章。1.实现原理 几种常见的实现方法,各有利弊。其中...2015-10-23
  • PHP实现递归无限级分类

    在一些复杂的系统中,要求对信息栏目进行无限级的分类,以增强系统的灵活性。那么PHP是如何实现无限级分类的呢?我们在本文中使用递归算法并结合mysql数据表实现无限级分类。 递归,简单的说就是一段程序代码的重复调用,当把...2015-10-23
  • C#类中static变量用法分析

    这篇文章主要介绍了C#类中static变量用法,实例分析了static变量使用技巧与相关注意事项,需要的朋友可以参考下...2020-06-25
  • mybatis-plus实体类主键策略有3种(小结)

    这篇文章主要介绍了mybatis-plus实体类主键策略有3种(小结),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-08-27
  • PHP中func_get_args(),func_get_arg(),func_num_args()的区别

    复制代码 代码如下:<?php function jb51(){ print_r(func_get_args()); echo "<br>"; echo func_get_arg(1); echo "<br>"; echo func_num_args(); } jb51("www","j...2013-10-04
  • ecshop商品无限级分类代码

    ecshop商品无限级分类代码 function cat_options($spec_cat_id, $arr) { static $cat_options = array(); if (isset($cat_options[$spec_cat_id]))...2016-11-25
  • PHP 一个完整的分页类(附源码)

    在php中要实现分页比起asp中要简单很多了,我们核心就是直接获取当前页面然后判断每页多少再到数据库中利用limit就可以实现分页查询了,下面我来详细介绍分页类实现程序...2016-11-25
  • PHP编程 SSO详细介绍及简单实例

    这篇文章主要介绍了PHP编程 SSO详细介绍及简单实例的相关资料,这里介绍了三种模式跨子域单点登陆、完全跨单点域登陆、站群共享身份认证,需要的朋友可以参考下...2017-01-25
  • 详解ES6实现类的私有变量的几种写法

    这篇文章主要介绍了详解ES6实现类的私有变量的几种写法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2021-02-10
  • PHP实现创建以太坊钱包转账等功能

    这篇文章主要介绍了PHP实现创建以太坊钱包转账等功能,对以太坊感兴趣的同学,可以参考下...2021-04-20
  • c#各种Timer类的区别与用法介绍

    System.Threading.Timer 是一个简单的轻量计时器,它使用回调方法并由线程池线程提供服务。在必须更新用户界面的情况下,建议不要使用该计时器,因为它的回调不在用户界面线程上发生...2020-06-25