php实现xml转换数组的方法示例,php自备函数

 代码如下,运行结果如下,{

 代码如下

<pre>
/**

<?php

  • 判断是否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>

$info= ‘<?xml version=”1.0″encoding=”utf-8″?>

<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>
/**

      <data>

  • 计算距离多少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>

        <GeocoderSearchResponse>

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

          <status>OK</status>

//将角度转为狐度
$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;

          <result>

}

            <location>

</pre>

              <lat>39.94921</lat>

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

              <lng>116.463619</lng>

  • @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>

            </location>

<pre>
/**

          <precise>0</precise>

  • 保存数组变量到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>

          <confidence>50</confidence>

<pre>
/**

          <level>脚本</level>

  • 递归检测一个值是否存在

  • @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>

          </result>

<pre>
/**

        </GeocoderSearchResponse>

  • 获取团队人数

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

        <GeocoderSearchResponse>

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 ++) {

          <status>OK</status>

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

          <result>

}
</pre>

            <location>

              <lat>39</lat>

              <lng>116</lng>

            </location>

          <precise>0</precise>

          <confidence>50</confidence>

          <level>脚本123</level>

          </result>

        </GeocoderSearchResponse>

      </data>’;

$xml= simplexml_load_string($info);

functionxml2array($xmlobject) {

  if($xmlobject) {

    foreach((array)$xmlobjectas$k=>$v) {

      $data[$k] = !is_string($v) ? xml2array($v) :$v;

    }

    return$data;

  }

}

$data= xml2array($xml);

var_dump($data);

?>

运行结果如下:

 代码如下

array(1) {

 [“GeocoderSearchResponse”]=>

 array(2) {

  [0]=>

  array(2) {

   [“status”]=>

   string(2)”OK”

   [“result”]=>

   array(4) {

    [“location”]=>

    array(2) {

     [“lat”]=>

     string(8)”39.94921″

     [“lng”]=>

     string(10)”116.463619″

    }

    [“precise”]=>

    string(1)”0″

    [“confidence”]=>

    string(2)”50″

    [“level”]=>

    string(6)”脚本”

   }

  }

  [1]=>

  array(2) {

   [“status”]=>

   string(2)”OK”

   [“result”]=>

   array(4) {

    [“location”]=>

    array(2) {

     [“lat”]=>

     string(2)”39″

     [“lng”]=>

     string(3)”116″

    }

    [“precise”]=>

    string(1)”0″

    [“confidence”]=>

    string(2)”50″

    [“level”]=>

    string(9)”脚本123″

   }

  }

 }

}