首页 » Web技术 » PHP » 正文

[笔记]几个简单有用的PHP函数

收藏几个简单的PHP函数,分别用于对象到数组转换、json到php数组转换功能、curl模拟POST以及根据链接获取内容。不直接使用json_decode()的原因是php json_decode()函数对\xA312此类字符支持不好。

1. 对象到数组转换

function objToArr($obj){
    if(!is_object($obj) && !is_array($obj)) {
        return $obj;
    }
    $arr = array();
    foreach($obj as $k => $v){
        $arr[$k] = $this->objToArr($v);
    }
    return $arr;
}

2. json到php数组转换

function simple_json_parser($json){
    $json = str_replace("{","",str_replace("}","", $json));
    $jsonValue = explode(",", $json);
    $arr = array();
    foreach($jsonValue as $v){
        $jValue = explode(":", $v);
        $arr[str_replace('"',"", $jValue[0])] = (str_replace('"', "", $jValue[1]));
    }
    return $arr;
}

3. curl 实现 GET / POST

function oauth_http($method,$header,$url,$data){
    $method = $method ? $method : 'get';
    if( $method == 'get') {
        $ch = curl_init ();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        $result = curl_exec ( $ch );
        curl_close ( $ch );
        return $result;
    } elseif ( $method == 'post' ) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, TRUE );
        curl_setopt ( $ch, CURLOPT_POST, TRUE );
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
        curl_setopt ( $ch, CURLOPT_URL, $url );
        curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        $ret = curl_exec ( $ch );
        curl_close ( $ch );
        return $ret;
    }
}

 

4. 获取链接内容(不存在file_get_contents() 时使用curl方法)

function get_url_contents($url)
{
    if (ini_get("allow_url_fopen") == "1")
        return file_get_contents($url);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_URL, $url);
    $result =  curl_exec($ch);
    curl_close($ch);

    return $result;
}

 

本文共 2 个回复

  • 单纯又可怜的女程序员 2015/11/19 10:27

    :grin:来复习一下

  • 单纯又可怜的女程序员 2015/11/19 10:28

    :lol: 我的表情呢

发表评论