xml分析类与xml创建函数

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

<?
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();

?>

<?php

class rss74 {

    // RSS feed title:
    var $title = "Untitled";
   
    // RSS description:
    var $desc = "";
   
    // RSS base url
    // -> Example: http://www.jonasjohn.de/
    var $base_url = "";
   
    // XSL file for the resulting RSS feed:
    var $xsl_file = 'rss.xsl';
   
    // RSS 2.0 Specification (URL):
    var $doc_url = 'http://blogs.law.harvard.edu/tech/rss';
   
    // Copyright text:
    // -> Example: Copyright 2006, Jonas John
    var $copyright = '';
   
    // RSS language setting:
    // Example: en-us, de-de, fr-fr
    var $language = 'en-us';
   
    // Managing editor and webmaster:
    // (should contain a E-Mail adress)
    var $managing_editor = '';
    var $webmaster = '';
   
    // Feedburner URL
    // Example: http://feeds.feedburner.com/codedump-rss
    // (If a FB URL is set, all requests except the Feedburner and Google
    // requests will be redricted to the feedburner URL)
    var $feedburner_url = '';
   
    // RSS generator:
    var $generator = 'rss74/v0.3';
   
    // Limit RSS entries to:
    // (Example: 20, 30, 40, 50, etc.)
    var $limit_entries = 20;

    // RSS items:
    var $items = array();

    // constructor:
    function rss74(){
    }  
   
    function add_entry($entry){   
   
        // create date key:
        $date = isset($entry['date']) ? $entry['date'] : time();  

        // add unique string:
        $date .= '_' . md5($entry['title']);
       
        $this->items[$date] = $entry;
    }
   
    function _get_val(&$array, $key){
        return isset($array[$key]) ? $array[$key] : '';
    }
   
    function _exists_val(&$array, $key){
        return isset($array[$key]);
    }
   
    function get_rss_headers($rss_webpath){
        return '<link rel="alternate" type="application/rss+xml" title="RSS" href="'.$rss_webpath.'" />';
    }
   
    function print_rss(){
        global $_SERVER;
   
        krsort($this->items);
        $this->items = array_slice($this->items, 0, $this->limit_entries);
       
        $first_item = array_keys($this->items);
        $first_item = $first_item[0];
       
        $last_change = $this->items[$first_item]['date'];
        header('Last-Modified: '.gmdate('D, d M Y H:i:s', $last_change).' GMT');
       
        header('Content-Type: text/xml; charset=utf-8');

        if (!empty($this->feedburner_url)){
            if (!preg_match("/feedburner/i", $_SERVER['HTTP_USER_AGENT']) and !preg_match("/google/i", $_SERVER['HTTP_USER_AGENT'])) {
                header('HTTP/1.1 301 Moved Permanently');
                header('Location: ' . $this->feedburner_url);
                print '<a href="'.$this->feedburner_url.'">Redirecting...</a>';
                return true;
            }
        }

        print '<?xml version="1.0" encoding="utf-8"?>' . " ";
       
        if ($this->xsl_file != '')
            print '<?xml-stylesheet href="rss.xsl" type="text/xsl" media="screen"?>' . " ";
       
        print '<!DOCTYPE rss [<!ENTITY % HTMLlat1 PUBLIC "-//W3C//ENTITIES Latin 1 for XHTML//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-lat1.ent">]>' . " ";
       
        print "<!-- Hello! This web page is a RSS file that is meant to be read by a RSS reader application. Look at http://en.wikipedia.org/wiki/RSS to learn more about RSS. -->";
       
        print '<rss version="2.0" xmlns:xhtml="http://www.w3.org/1999/xhtml">' . " ";
        print '<channel>' . " ";
       
        print " ".'<title>'.htmlentities($this->title).'</title>' . " ";
       
        if (!empty($this->desc))
            print " ".'<description>'.htmlentities($this->desc).'</description>' . " ";
       
        if (!empty($this->base_url))
            print " ".'<link>'.htmlentities($this->base_url).'</link>' . " ";
       
        print " ".'<lastBuildDate>'.date('r', time()).'</lastBuildDate>' . " ";
        print " ".'<pubDate>'.date('r', time()).'</pubDate>' . " ";
       
        if (!empty($this->generator))
            print " ".'<generator>'.$this->generator.'</generator>' . " ";
       
        if (!empty($this->copyright))
            print " ".'<copyright>'.$this->copyright.'</copyright>' . " ";
           
        if (!empty($this->doc_url))
            print " ".'<docs>'.$this->doc_url.'</docs>' . " ";
       
        if (!empty($this->language))
            print " <language>".$this->language."</language> ";
           
        if (!empty($this->managing_editor))
            print " <managingEditor>".$this->managing_editor."</managingEditor> ";

        if (!empty($this->webmaster))
            print " <webMaster>".$this->webmaster."</webMaster> ";


        while(list($num, $item) = each($this->items)){
     
            print " <item> ";
            print " <title>".htmlentities($this->_get_val($item, 'title'))."</title> ";
           
            if ($this->_exists_val($item, 'url')){
                print " <link>".$this->_get_val($item, 'url')."</link> ";
                print " <guid isPermaLink="true">".$this->_get_val($item, 'url')."</guid> ";
            }
           
            if ($this->_exists_val($item, 'desc'))
                print " <description><![CDATA[".$this->_get_val($item, 'desc')."]]></description> ";
           
            if ($this->_exists_val($item, 'date')){
                print " <pubDate>".date('r', intval($this->_get_val($item, 'date')))."</pubDate> ";
            }
       
            $cats = array();
            while(list($cn, $citem) = each($cats)){
                print " <category>$citem</category> ";
            }
               
            print " </item> ";
            
        }

        print " </channel> ";
        print "</rss>";
       
        return true;
       
    }
}

实例

 include('inc.rss74.php');

    // RSS items list:
    $example_list = array();   
       
    /*
    ** Create some test entries:
    */
   
    $m = rand(8, 30);
    for ($x = 0; $x < $m; $x++){
   
        // create a random UNIX-Timestamp:
        $date = rand(1166000000, 1166400000);
   
        $example_list[] = array(
            'title' => 'Example RSS message #' . $x,
            'url' => 'http://www.jonasjohn.de/#' . $x,
            'desc' => 'This is a example message from RSS74!',
            'date' => $date
        );
   
    }
   
   
    // create new RSS object:
    $rss = new rss74();
   
    /*
    ** Set RSS informations:
    */
   
    // RSS title:
    $rss->title = 'RSS example 2';
   
    // RSS description:
    $rss->desc = 'This feed shows some random entries.';
   
    // base URL of your homepage:
    $rss->base_url = 'http://www.example.org/';
   
    // limit entry count to 20
    $rss->limit_entries = 20;
   
    // RSS Editor
    $rss->managing_editor = 'Yourname <yourname@example.org>';

    // Webmaster name
    $rss->webmaster = 'Yourname <yourname@example.org>';
   
    // language:
    $rss->language = 'en-us';
   
    // Copyright message:
    $rss->copyright = 'Copyright 2006, Yourname';
   
    // Set Feedburner adress:
    //$rss->feedburner_url = 'http://feeds.feedburner.com/codedump-rss';
    // (empty) = No redirection

    // Set "xsl_file" to empty to disable the XSL file:
    $rss->xsl_file = '';

    // Add entries to the RSS object:
    while (list($date, $entry) = each($example_list)){
              
        $rss->add_entry(array(
            'title'     => $entry['title'],
            'url'       => $entry['url'],
            'desc'      => $entry['desc'],
            'date'      => $entry['date']
        ));
   
    }
   
    // let rss74 do the rest:
    $rss->print_rss();

?>

 

 <?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>

 

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

[!--infotagslink--]

相关文章

  • php正确禁用eval函数与误区介绍

    eval函数在php中是一个函数并不是系统组件函数,我们在php.ini中的disable_functions是无法禁止它的,因这他不是一个php_function哦。 eval()针对php安全来说具有很...2016-11-25
  • php中eval()函数操作数组的方法

    在php中eval是一个函数并且不能直接禁用了,但eval函数又相当的危险了经常会出现一些问题了,今天我们就一起来看看eval函数对数组的操作 例子, <?php $data="array...2016-11-25
  • Python astype(np.float)函数使用方法解析

    这篇文章主要介绍了Python astype(np.float)函数使用方法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-06-08
  • Python中的imread()函数用法说明

    这篇文章主要介绍了Python中的imread()函数用法说明,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2021-03-16
  • C# 中如何取绝对值函数

    本文主要介绍了C# 中取绝对值的函数。具有很好的参考价值。下面跟着小编一起来看下吧...2020-06-25
  • C#学习笔记- 随机函数Random()的用法详解

    下面小编就为大家带来一篇C#学习笔记- 随机函数Random()的用法详解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25
  • 金额阿拉伯数字转换为中文的自定义函数

    CREATE FUNCTION ChangeBigSmall (@ChangeMoney money) RETURNS VarChar(100) AS BEGIN Declare @String1 char(20) Declare @String2 char...2016-11-25
  • Android开发中findViewById()函数用法与简化

    findViewById方法在android开发中是获取页面控件的值了,有没有发现我们一个页面控件多了会反复研究写findViewById呢,下面我们一起来看它的简化方法。 Android中Fin...2016-09-20
  • C++中 Sort函数详细解析

    这篇文章主要介绍了C++中Sort函数详细解析,sort函数是algorithm库下的一个函数,sort函数是不稳定的,即大小相同的元素在排序后相对顺序可能发生改变...2022-08-18
  • PHP用strstr()函数阻止垃圾评论(通过判断a标记)

    strstr() 函数搜索一个字符串在另一个字符串中的第一次出现。该函数返回字符串的其余部分(从匹配点)。如果未找到所搜索的字符串,则返回 false。语法:strstr(string,search)参数string,必需。规定被搜索的字符串。 参数sea...2013-10-04
  • PHP函数分享之curl方式取得数据、模拟登陆、POST数据

    废话不多说直接上代码复制代码 代码如下:/********************** curl 系列 ***********************///直接通过curl方式取得数据(包含POST、HEADER等)/* * $url: 如果非数组,则为http;如是数组,则为https * $header:...2014-06-07
  • php中的foreach函数的2种用法

    Foreach 函数(PHP4/PHP5)foreach 语法结构提供了遍历数组的简单方式。foreach 仅能够应用于数组和对象,如果尝试应用于其他数据类型的变量,或者未初始化的变量将发出错误信息。...2013-09-28
  • C语言中free函数的使用详解

    free函数是释放之前某一次malloc函数申请的空间,而且只是释放空间,并不改变指针的值。下面我们就来详细探讨下...2020-04-25
  • JavaScript动态创建div属性和样式示例代码

    1.创建div元素: Javascript代码 复制代码 代码如下: <scripttypescripttype="text/javascript"> functioncreateElement(){ varcreateDiv=document.createElement("div"); createDiv.innerHTML="Testcreateadiveleme...2013-10-13
  • PHP函数strip_tags的一个bug浅析

    PHP 函数 strip_tags 提供了从字符串中去除 HTML 和 PHP 标记的功能,该函数尝试返回给定的字符串 str 去除空字符、HTML 和 PHP 标记后的结果。由于 strip_tags() 无法实际验证 HTML,不完整或者破损标签将导致更多的数...2014-05-31
  • SQL Server中row_number函数的常见用法示例详解

    这篇文章主要给大家介绍了关于SQL Server中row_number函数的常见用法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧...2020-12-08
  • PHP加密解密函数详解

    分享一个PHP加密解密的函数,此函数实现了对部分变量值的加密的功能。 加密代码如下: /* *功能:对字符串进行加密处理 *参数一:需要加密的内容 *参数二:密钥 */ function passport_encrypt($str,$key){ //加密函数 srand(...2015-10-30
  • JS创建Tag标签的方法详解

    这篇文章主要介绍了JS创建Tag标签的方法,结合具体实例形式分析了javascript动态操作页面HTML元素实现tag标签功能的步骤与相关操作技巧,需要的朋友可以参考下...2017-06-15
  • php的mail函数发送UTF-8编码中文邮件时标题乱码的解决办法

    最近遇到一个问题,就是在使用php的mail函数发送utf-8编码的中文邮件时标题出现乱码现象,而邮件正文却是正确的。最初以为是页面编码的问题,发现页面编码utf-8没有问题啊,找了半天原因,最后找到了问题所在。 1.使用 PEAR 的...2015-10-21
  • C#中加载dll并调用其函数的实现方法

    下面小编就为大家带来一篇C#中加载dll并调用其函数的实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2020-06-25