php自备函数,读取团购网址的api的php程序

<?
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’]”;

读取团购网站的api的php教程程序

$arr = array(
 array(“”,”美团网”),

);

class AminoAcid {
    var $name;
    var $symbol;
    var $code;
    var $type;
    function AminoAcid ($aa){
        foreach ($aa as $k=>$v)
            $this->$k = $aa[$k];
    }
}
function readDatabase($filename,$label){
    $data = implode(“”,file($filename));
    $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, $data, $values, $tags);
    xml_parser_free($parser);
    foreach ($tags as $key=>$val) {
        if ($key == $label) {
            $molranges = $val;
            for ($i=0; $i < count($molranges); $i+=2) {
                $offset = $molranges[$i] + 1;
                $len = $molranges[$i + 1] – $offset;
                $tdb[] = parseMol(array_slice($values, $offset,
$len));
            }
        } else {
            continue;
        }
    }
    return $tdb;
}
function parseMol($mvalues){
    for ($i=0; $i < count($mvalues); $i++) {
        $mol[$mvalues[$i][“tag”]] = $mvalues[$i][“value”];
    }
    return new AminoAcid($mol);
}

foreach($arr as $key => $value){
   $r = readDatabase($value[0],$value[1]);
   print_r($r);//打字与印刷出来解析出来的信息
 }

<pre>
/**

php 生成xml代码class XMLParser {

  eval(‘$this->tree’.”$this->locationstring = array(); “);
  eval(‘$this->tree’.”$this->locationstring”.”[‘nodes’] = 0; “);

  • 剖断是不是SSL左券
  • @return boolean
    */
    function is_ssl() {
    if(isset($_SERVER[‘HTTPS’]) && (‘1’ == $_SERVER[‘HTTPS’] ||
    ‘on’ == strtolower($_SERVER[‘HTTPS’]))){
    return true;
    }elseif(isset($_SERVER[‘SERVER_PORT’]) && (‘443’ ==
    $_SERVER[‘SERVER_PORT’] )) {
    return true;
    }
    return false;
    //真为https假为http
    }
    </pre>

 function getChildren($vals, &$i) {

 }
 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; “);

<pre>
//http请求
function https_request($url, $data = null)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if (!empty($data)){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
</pre>
<pre>
//总计时间某些秒以前
function format_date($time){
$time = strtotime($time);
$t=time()-$time;
$f=array(
‘31536000’=>’年’,
‘2592000’=>’个月’,
‘604800’=>’星期’,
‘86400’=>’天’,
‘3600’=>’小时’,
’60’=>’分钟’,
‘1’=>’秒’
);
foreach ($f as $k=>$v) {
if (0 !=$c=floor($t/(int)$k)) {
return $c.$v.’前’;
}
}
}
</pre>
<pre>
/**

  $children = array();
  if(isset($vals[$i][‘value’])) {
   $children[‘VALUE’] = $vals[$i][‘value’];
  }

  }
  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’]”;

  • 计量距离有个别km
  • @param [float] $s [距离 :128.9]
  • @return [string] [200m 100km >30km]
    */
    function convertMeter($s){
    if($s /1000 <1){
    return sprintf(“%.0f”,$s).’m’;
    }elseif($s /1000 >=1 && ($s /1000 < 30)){
    return sprintf(“%.2f”, ($s /1000)).”km”;
    }elseif($s /1000 > 30){
    return “>30km”;
    }
    }
    </pre>

  while(++$i < count($vals)) {
   switch($vals[$i][‘type’]) {

  eval(‘$this->tree’.”$this->locationstring”.”[‘nodes’] =
$this->location; “);   
 }
 public function gettree()
 { return $this->tree;
 }
}

<pre>
/**
*求多个已知经纬度之间的离开,单位为米
*@param lng1,lng2 经度
*@param lat1,lat2 纬度
*@return float 距离,单位米
*@author
www.Alixixi.com
**/
//function getdistance($lng1,$lat1,$lng2,$lat2){
function getdistance($in_location,$coordination){
$in_location = explode(‘,’,$in_location);
list($lng1, $lat1) = $in_location;
$coordination = explode(‘,’,$coordination);
list($lng2, $lat2) = $coordination;

   case ‘cdata’:
    if(isset($children[‘VALUE’])) {
     $children[‘VALUE’] .= $vals[$i][‘value’];
    } else {
     $children[‘VALUE’] = $vals[$i][‘value’];
    }
    break;

/***************************************************
**  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)
php自备函数,读取团购网址的api的php程序。 { $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;

//将角度转为狐度
$radLat1=deg2rad($lat1);//deg2rad()函数将角度转换为弧度
$radLat2=deg2rad($lat2);
$radLng1=deg2rad($lng1);
$radLng2=deg2rad($lng2);
$a=$radLat1-$radLat2;
$b=$radLng1-$radLng2;
$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137*1000;
//$s = convertMeter($s);
return $s;

   case ‘complete’:
    if(isset($vals[$i][‘attributes’])) {
     $children[$vals[$i][‘tag’]][][‘ATTRIBUTES’] =
$vals[$i][‘attributes’];
     $index = count($children[$vals[$i][‘tag’]]) – 1;

    
$data=eregi_replace(“>”.”[[:space:]]+”.”<“,”><“,$data);
       $data=str_replace(“&”,”&”,$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(“&”,”&”,$this->tree->gettree());
  return $data[‘node:1’];
 }
 
 
}

}

     if(isset($vals[$i][‘value’])) {
      $children[$vals[$i][‘tag’]][$index][‘VALUE’] =
$vals[$i][‘value’];
     } else {
      $children[$vals[$i][‘tag’]][$index][‘VALUE’] = ”;
     }
    } else {
     if(isset($vals[$i][‘value’])) {
      $children[$vals[$i][‘tag’]][][‘VALUE’] =
$vals[$i][‘value’];
     } else {
      $children[$vals[$i][‘tag’]][][‘VALUE’] = ”;
     }
    }
    break;

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

</pre>

   case ‘open’:
    if(isset($vals[$i][‘attributes’])) {
     $children[$vals[$i][‘tag’]][][‘ATTRIBUTES’] =
$vals[$i][‘attributes’];
     $index = count($children[$vals[$i][‘tag’]]) – 1;
     $children[$vals[$i][‘tag’]][$index] =
array_merge($children[$vals[$i][‘tag’]][$index],
$this->getChildren($vals, $i));
    } else {
     $children[$vals[$i][‘tag’]][] =
$this->GetChildren($vals, $i);
    }
    break;

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);
  }
  
 }

<pre>
/**
*获得html文本里的img

   case ‘close’:
    return $children;
   }
  }
 }

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

  • @param string $content
  • @return array
    */
    function sp_getcontent_imgs($content){
    import(“phpQuery”);
    \phpQuery::newDocumentHTML($content);
    $pq=pq();
    $imgs=$pq->find(“img”);
    $imgs_data=array();
    if($imgs->length()){
    foreach ($imgs as $img){
    $img=pq($img);
    $im[‘src’]=$img->attr(“src”);
    $im[‘title’]=$img->attr(“title”);
    $im[‘alt’]=$img->attr(“alt”);
    $imgs_data[]=$im;
    }
    }
    \phpQuery::$documents=null;
    return $imgs_data;
    }
    </pre>

 function getXMLTree($data) {

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

<pre>
/**

  $parser = xml_parser_create(‘UTF-8’);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 0);
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parse_into_struct($parser, $data, $vals, $index);
  xml_parser_free($parser);

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

  • 封存数组变量到php文件
    /
    function sp_save_var($path,$value){
    $ret = file_put_contents($path, “<?php\treturn ” .
    var_export($value, true) . “;?>”);
    return $ret;
    }
    </pre>
    <pre>
    /
    *
  • 专擅字符串生成
  • @param int $len 生成的字符串长度
  • @return string
    */
    function sp_random_string($len = 6,$type=1) {
    if($type){
    $chars = array(
    “a”, “b”, “c”, “d”, “e”, “f”, “g”, “h”, “i”, “j”, “k”,
    “l”, “m”, “n”, “o”, “p”, “q”, “r”, “s”, “t”, “u”, “v”,
    “w”, “x”, “y”, “z”, “A”, “B”, “C”, “D”, “E”, “F”, “G”,
    “H”, “I”, “J”, “K”, “L”, “M”, “N”, “O”, “P”, “Q”, “R”,
    “S”, “T”, “U”, “V”, “W”, “X”, “Y”, “Z”, “0”, “1”, “2”,
    “3”, “4”, “5”, “6”, “7”, “8”, “9”
    );
    $charsLen = count($chars) – 1;
    shuffle($chars); // 将数组打乱
    $output = “”;
    for ($i = 0; $i < $len; $i++) {
    $output .= $chars[mt_rand(0, $charsLen)];
    }
    }else{
    return mt_rand(1000, 9999);
    }
    return $output;
    }
    </pre>

  $tree = array();
  $i = 0;

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

<pre>
/**

  if(isset($vals[$i][‘attributes’])) {
   $tree[$vals[$i][‘tag’]][][‘ATTRIBUTES’] =
$vals[$i][‘attributes’];
   $index = count($tree[$vals[$i][‘tag’]]) – 1;
   $tree[$vals[$i][‘tag’]][$index] = 
array_merge($tree[$vals[$i][‘tag’]][$index],
$this->getChildren($vals, $i));
  } else {
   $tree[$vals[$i][‘tag’]][] = $this->getChildren($vals,
$i);
  }
  return $tree;
 }
}

   
  
  $location = ereg_replace(“^/”, “”,$location);
  $location = ereg_replace(“/$”, “”,$location);

  • 递归检查实验多个值是还是不是留存

  • @param [string] $value [要物色的字符串]

  • @param [array] $array [自己商酌外省的数组]

  • @return [bool] [true/false]
    */
    function deep_in_array($value, $array) {
    foreach($array as $item) {
    if(!is_array($item)) {//如若不是数组
    if ($item == $value) {
    return true;
    } else {
    continue;
    }
    }

     if(in_array($value, $item)) {  //如果是数组
         return true;      
     } else if(deep_in_array($value, $item)) {  //递归调用
         return true;      
     }  
    

    }
    return false;
    }
    </pre>

  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;
  

<pre>
/**

 }
 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);

  • 取得团队人数

  • @param [string] $name 介绍人姓名

  • @param [int] $rank 获取下级几级

  • @param [bool] $activation 是不是获得激活的会员

  • @return [type] [description]
    */
    function getTeam($name,$rank=26,$activation=false,$lev=0){
    global $num ;
    $num++;
    if(!$name) return false;
    if($activation){//获取激活的部属会员
    $userList =
    M(‘member’)->field(‘id,account,active’)->where(array(‘references’=>$name,’active’=>1))->select();
    }else{
    $userList =
    M(‘member’)->field(‘id,account,active’)->where(array(‘references’=>$name))->select();
    }
    if($userList && $num<=$rank){
    foreach ($userList as $key => $value) {
    $userList[$key][‘lev’] = $num;
    $userList[‘list’] =
    getTeam($value[‘account’],$rank,$activation);
    $arr[] = $userList;
    }
    }
    return $arr;
    }
    </pre>
    <pre>
    function arr_to_xml($arr, $dom = 0, $item = 0) {
    if (! $dom) {
    $dom = new DOMDocument (“1.0″,”UTF-8”);
    }

    if (! $item) {
    $ccc = array_keys ( $arr );
    if ($ccc [0] == ‘envelope’) {
    $str_head = ‘request’;
    } else {
    $str_head = ‘envelope’;
    }
    $item = $dom->createElement ( $str_head );
    $dom->appendChild ( $item );
    }
    foreach ( $arr as $key => $val ) {
    $itemx = $dom->createElement ( is_string ( $key ) ? $key :
    “record” );
    $item->appendChild ( $itemx );
    if (! is_array ( $val )) {
    $text = $dom->createTextNode ( $val );
    $itemx->appendChild ( $text );
    } else {
    arr_to_xml ( $val, $dom, $itemx );
    }
    }

    return $dom->saveXML ();
    }

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

function xml_to_array($xml) {
$reg = “/<(\w+)[^>]?>([\x00-\xFF]?)<\/\1>/”;
if (preg_match_all ( $reg, $xml, $matches )) {
$count = count ( $matches [0] );
$arr = array ();
for($i = 0; $i < $count; $i ++) {

  $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);

        $key = $matches [1] [$i];   

        $val = xml_to_array ( $matches [2] [$i] ); // 递归
        if (array_key_exists ( $key, $arr )) {
            if (is_array ( $arr [$key] )) {
                if (! array_key_exists ( 0, $arr [$key] )) {
                    $arr [$key] = array (
                            $arr [$key] 
                    );
                }
            } else {

                $arr [$key] = array (
                        $arr [$key] 
                );
            }
            $arr [$key] [] = $val;
        } else {

            $arr [$key] = $val;
        }
    }
    return $arr;
} else {
    return $xml;
}

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

}
</pre>

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

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”,””);

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地图