file_get_contents 和curl的使用

file_get_contents 方式
<?php
function Post($url, $post = null) {
    if (is_array($post)) {
        ksort($post);
        $content = http_build_query($post);
        $content_length = strlen($content);
        $options = array(
            'http' => array(
                'method' => 'POST',
                'header' =>
                "Content-type: application/x-www-form-urlencoded\r\n" .
                "Content-length: $content_length\r\n",
                'content' => $content
            )
        );
        return file_get_contents($url, false, stream_context_create($options));
    }
}
 
$data = array
    (
    'url' => 'http://www.waqiang.com/index.php/url/shorten',
    'submit' => 'submit',
);
 
$response = Post('http://www.waqiang.com/index.php/url/shorten', $data);
$reg = '#[\'"](http:(//|\\/\\/)t\.cn((/|\\/)([^\'"/]+)(/|\\/)?|(/|\\/)))[\'"]#';
preg_match_all($reg, $response, $match);
var_dump($match);

 

curl 方式
<?php
function shorturl($long_url) {
    $url = 'http://www.waqiang.com/index.php/url/shorten';
    $data = array(
        'url' => $long_url,
        'submit' => 'Submit'
    );
    $curlObj = curl_init();
    $options = array(
        CURLOPT_URL => $url,
        CURLOPT_POST => TRUE, //使用post提交
        CURLOPT_RETURNTRANSFER => TRUE, //接收服务端范围的html代码而不是直接浏览器输出
        CURLOPT_TIMEOUT => 4,
        CURLOPT_POSTFIELDS => http_build_query($data), //post的数据
    );
    curl_setopt_array($curlObj, $options);
    $response = curl_exec($curlObj);
    curl_close($curlObj);
    return $response;
}
 
$result = shorturl('http://www.waqiang.com/index.php/url/shorten');
$reg = '#[\'"](http:(//|\\/\\/)t\.cn((/|\\/)([^\'"/]+)(/|\\/)?|(/|\\/)))[\'"]#';
preg_match_all($reg, $result, $match);
var_dump($match);

 

 

出处:http://www.cnblogs.com/quinnxu/p/3493266.html

posted on 2015-02-10 14:39  rgwybb  阅读(211)  评论(0编辑  收藏  举报

导航