2011-02-23 3 views
0

je le code JSON suivant:Affichage JSON à l'URL en utilisant curl PHP

{ "nom d'utilisateur": "user1", "mot de passe": "123456"}

que je dois passer à une url , permet de dire: http://api.mywebsite.com

Je suis un newb extrême php, donc j'ai suivi un tutoriel boucle, mais voici mon actuel code PHP:

<?php 

function get_web_page($url) 
{ 
    $options = array(
     CURLOPT_RETURNTRANSFER => true,  // return web page 
     CURLOPT_HEADER   => true, // don't return headers 
     CURLOPT_FOLLOWLOCATION => true,  // follow redirects 
     CURLOPT_ENCODING  => "",  // handle compressed 
     CURLOPT_USERAGENT  => "spider", // who am i 
     CURLOPT_AUTOREFERER => true,  // set referer on redirect 
     CURLOPT_CONNECTTIMEOUT => 120,  // timeout on connect 
     CURLOPT_TIMEOUT  => 120,  // timeout on response 
     CURLOPT_MAXREDIRS  => 10,  // stop after 10 redirects 
    ); 

    $ch  = curl_init($url); 
    curl_setopt_array($ch, $options); 
    $content = curl_exec($ch); 
    $err  = curl_errno($ch); 
    $errmsg = curl_error($ch); 
    $header = curl_getinfo($ch); 
    curl_close($ch); 

    $header['errno'] = $err; 
    $header['errmsg'] = $errmsg; 
    $header['content'] = $content; 
    return $header; 

} 

?> 

Répondre

1

Vous pourriez vouloir regarder dans le CURLOPT_POSTFIELDS ET CURLOPT_POS T options. Ceux-ci vous permettent de faire une requête POST et de transmettre l'ensemble de données dans CURLOPT_POSTFIELDS dans la requête.

Quelque chose dans les lignes de ce:

$body = 'bar=1&foo=2&baz=3'; 
$c = curl_init ($url); 
curl_setopt ($c, CURLOPT_POST, true); 
curl_setopt ($c, CURLOPT_POSTFIELDS, $body); 
curl_setopt ($c, CURLOPT_RETURNTRANSFER, true); 
0

Lorsque vous souhaitez utiliser GET normale Params:

$jsonString ='{"username":"user1","password":"123456"}'; 
$params = json_decode($jsonString); 

$getParams = ''; 
$first = true; 
foreach ($params as $key => $param){ 
    if ($first){ 
     $getParams .= '?'; 
     $first = false; 
    } else{ 
     $getParams .= '&'; 
    } 

    $getParams .= $key .'=' .$param; 
} 

echo $getParams; 
get_web_page($url . $getParams);