2011-04-02 77 views
18

Cuando uso la siguiente URL en el navegador, entonces me pide que descargue un archivo de texto con contenido JSOn.¿Obtener contenido de archivo desde la URL?

https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json

(Haga clic encima URL ver el contenido archivo descargado)

Ahora quiero crear una página PHP. Quiero que cuando llamo a esta página php, debe llamar a la URL anterior y obtener el contenido (formato json) del archivo y mostrarlo en la pantalla.

¿Cómo puedo hacer esto?

Respuesta

45

Dependiendo de la configuración de PHP, esto puede ser un sencillo como usar:

$jsonData = json_decode(file_get_contents('https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json')); 

Sin embargo, si allow_url_fopen no está habilitada en el sistema, se puede leer los datos a través de CURL de la siguiente manera:

<?php 
    $curlSession = curl_init(); 
    curl_setopt($curlSession, CURLOPT_URL, 'https://chart.googleapis.com/chart?cht=p3&chs=250x100&chd=t:60,40&chl=Hello|World&chof=json'); 
    curl_setopt($curlSession, CURLOPT_BINARYTRANSFER, true); 
    curl_setopt($curlSession, CURLOPT_RETURNTRANSFER, true); 

    $jsonData = json_decode(curl_exec($curlSession)); 
    curl_close($curlSession); 
?> 

Por cierto, si solo desea los datos JSON sin procesar, simplemente elimine el json_decode.

2

Use file_get_contents en combinación con json_decode y echo.

+0

Estoy usando file_get_contents para obtener contenido, pero no es JSON cuando lo repito. Está mostrando algunos caracteres especiales. – Awan

+0

@Awan ¿alguna vez fue capaz de resolver esto? También estoy viendo personajes especiales. – jewel

1
$url = "https://chart.googleapis...."; 
$json = file_get_contents($url); 

Ahora podrá repetir la variable $ JSON, si lo que desea es mostrar la salida, o puede decodificarlo, y hacer algo con él, así:

$data = json_decode($json); 
var_dump($data); 
10

1) métodos más simples locales

<?php 
echo readfile("http://example.com/"); //needs "Allow_url_include" enabled 
//OR 
echo include("http://example.com/"); //needs "Allow_url_include" enabled 
//OR 
echo file_get_contents("http://example.com/"); 
//OR 
echo stream_get_contents(fopen('http://example.com/', "rb")); //you may use "r" instead of "rb" //needs "Allow_url_fopen" enabled 
?> 

2) mejor manera CURL:

echo get_remote_data('http://example.com'); // GET request 
echo get_remote_data('http://example.com', "var2=something&var3=blabla"); // POST request 

//See Updates and explanation at: https://github.com/tazotodua/useful-php-scripts/ 
function get_remote_data($url, $post_paramtrs=false) 
{ 
    $c = curl_init(); 
    curl_setopt($c, CURLOPT_URL, $url); 
    curl_setopt($c, CURLOPT_RETURNTRANSFER, 1); 
    if($post_paramtrs) 
    { 
     curl_setopt($c, CURLOPT_POST,TRUE); 
     curl_setopt($c, CURLOPT_POSTFIELDS, "var1=bla&".$post_paramtrs); 
    } 
    curl_setopt($c, CURLOPT_SSL_VERIFYHOST,false); 
    curl_setopt($c, CURLOPT_SSL_VERIFYPEER,false); 
    curl_setopt($c, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows NT 6.1; rv:33.0) Gecko/20100101 Firefox/33.0"); 
    curl_setopt($c, CURLOPT_COOKIE, 'CookieName1=Value;'); 
    curl_setopt($c, CURLOPT_MAXREDIRS, 10); 
    $follow_allowed= (ini_get('open_basedir') || ini_get('safe_mode')) ? false:true; 
    if ($follow_allowed) 
    { 
     curl_setopt($c, CURLOPT_FOLLOWLOCATION, 1); 
    } 
    curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 9); 
    curl_setopt($c, CURLOPT_REFERER, $url); 
    curl_setopt($c, CURLOPT_TIMEOUT, 60); 
    curl_setopt($c, CURLOPT_AUTOREFERER, true); 
    curl_setopt($c, CURLOPT_ENCODING, 'gzip,deflate'); 
    $data=curl_exec($c); 
    $status=curl_getinfo($c); 
    curl_close($c); 
    preg_match('/(http(|s)):\/\/(.*?)\/(.*\/|)/si', $status['url'],$link); $data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/|\/)).*?)(\'|\")/si','$1=$2'.$link[0].'$3$4$5', $data); $data=preg_replace('/(src|href|action)=(\'|\")((?!(http|https|javascript:|\/\/)).*?)(\'|\")/si','$1=$2'.$link[1].'://'.$link[3].'$3$4$5', $data); 
    if($status['http_code']==200) 
    { 
     return $data; 
    } 
    elseif($status['http_code']==301 || $status['http_code']==302) 
    { 
     if (!$follow_allowed) 
     { 
      if (!empty($status['redirect_url'])) 
      { 
       $redirURL=$status['redirect_url']; 
      } 
      else 
      { 
       preg_match('/href\=\"(.*?)\"/si',$data,$m); 
       if (!empty($m[1])) 
       { 
        $redirURL=$m[1]; 
       } 
      } 
      if(!empty($redirURL)) 
      { 
       return call_user_func(__FUNCTION__, $redirURL, $post_paramtrs); 
      } 
     } 
    } 
    return "ERRORCODE22 with $url!!<br/>Last status codes<b/>:".json_encode($status)."<br/><br/>Last data got<br/>:$data"; 
} 

AVISO: Se HANDES automáticamente FOLLOWLOCATION problemas + URL remotos son re corregido automáticamente! (src = "./ imageblabla.png" --------> src = "http://example.com/path/imageblabla.png")

pson Servidores de distribución GNU/Linux, usted puede necesitar instalar el paquete php5-curl para usarlo.

+0

Gracias hombre ,. fue muy útil. –

Cuestiones relacionadas