如何通过curl读取数据并将结果返回到JSON

时间:2015-08-07 08:28:10

标签: php arrays json curl

如何在文件中显示3个不同的直接链接?

我有3个标签ID的链接,低itag-5,中18,HD-22如下所示。

http://excample.com/'.$id.'/direct/5/'
http://excample.com/'.$id.'/direct/18/'
http://excample.com/'.$id.'/direct/22/' 

以上链接的重定向质量不同。

我想要输出如下面的网址

http://server1.excample.com/vimotube.php?id=5lf9GWCQcMA

1 个答案:

答案 0 :(得分:1)

您可以使用json_encode将数据恢复为JSON格式

完整代码

<?php

function get_final_url( $url, $timeout = 5 )
{
    $url = str_replace( "&amp;", "&", urldecode(trim($url)) );

    $ch = curl_init();
    curl_setopt( $ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1" );
    curl_setopt( $ch, CURLOPT_URL, $url );
    curl_setopt( $ch, CURLOPT_FOLLOWLOCATION, true );
    curl_setopt( $ch, CURLOPT_ENCODING, "" );
    curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt( $ch, CURLOPT_AUTOREFERER, true );
    curl_setopt( $ch, CURLOPT_CONNECTTIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_TIMEOUT, $timeout );
    curl_setopt( $ch, CURLOPT_MAXREDIRS, 10 );
    $content = curl_exec( $ch );
    $response = curl_getinfo( $ch );
    curl_close ( $ch );

    if ($response['http_code'] == 301 || $response['http_code'] == 302)
    {
        ini_set("user_agent", "Mozilla/5.0 (Windows; U; Windows NT 5.1; rv:1.7.3) Gecko/20041001 Firefox/0.10.1");
        $headers = get_headers($response['url']);

        $location = "";
        foreach( $headers as $value )
        {
            if ( substr( strtolower($value), 0, 9 ) == "location:" )
                return get_final_url( trim( substr( $value, 9, strlen($value) ) ) );
        }
    }

    if
    (
        preg_match("/window\.location\.replace\('(.*)'\)/i", $content, $value) ||
        preg_match("/window\.location\=\"(.*)\"/i", $content, $value)
    )
    {
        return get_final_url ( $value[1] );
    }
    else
    {
        return $response['url'];
    }
}

if(!isset($_GET['id']))
exit('Invalid URL.');

    $id = $_GET['id'];
    $url1 = 'http://excample.com/'.$id.'/direct/5/';
    $url2 = 'http://excample.com/'.$id.'/direct/18/';
    $url3 = 'http://excample.com/'.$id.'/direct/22/';

    $json = array('5' => array('quality' => '5', 'type' => 'video/x-flv', 'url' => get_final_url($url1)),'18' => array('quality' => '18', 'type' => 'video/mp4', 'url' => get_final_url($url2)),'22' => array('quality' => '22', 'type' => 'video/mp4', 'url' => get_final_url($url3)));

    header('Content-type: application/json');
    echo json_encode($json);
?>