如何从PHP发布数据到api?

时间:2016-03-27 09:04:58

标签: php api

我有需要发送到api的数据。数据是在PHP中。 我如何将它传递给api?

这是我的php代码,其中包含必须发送到api的数据。

<?php 
$username="root";$password="";$database="format";
mysql_connect("localhost",$username,$password);
@mysql_select_db($database) or die( "Unable to select database");
$ead="quikr.com";
$query=mysql_query("select * from mailformat where partner_from_email ='$ead'");

$row = mysql_fetch_array($query);

$f1 = $row['customer_name_from'];
$f2 = $row['customer_name_to'];
$f3 = $row['customer_city_from'];
$f4 = $row['customer_city_to'];
$f5 = $row['customer_service_from'];
$f6 = $row['customer_service_to'];
$f7 = $row['customer_preference_from'];
$f8 = $row['customer_preference_to'];
$f9 = $row['customer_mail_from'];
$f10 = $row['customer_mail_to'];
$f11 = $row['customer_phone_from'];
$f12 = $row['customer_phone_to'];
if(strcmp($f12,"null")==0)
$f12="EOL";
$input="Name\n\nSindhuj City :Chennai- Service Pest Preference redident Mail coail.com Phone 9043234342 EOL";
$input=preg_replace('/\R/','', $input); //to remove all kinds of \n
$input=preg_replace('/[^a-z0-9.]/i', ' ', $input); // to remove all special characters


$ftwo='/'.$f1.'(.*?)'.$f2.'/'; //reg expr to get values between field1 and field2.
preg_match($ftwo,$input, $display);
print_r($display[1]);
$ftwo='/'.$f3.'(.*?)'.$f4.'/'; 
preg_match($ftwo,$input, $display);
print_r($display[1]);
$ftwo='/'.$f5.'(.*?)'.$f6.'/'; 
preg_match($ftwo,$input, $display);
print_r($display[1]);
$ftwo='/'.$f7.'(.*?)'.$f8.'/';
preg_match($ftwo,$input, $display);
print_r($display[1]);
$ftwo='/'.$f9.'(.*?)'.$f10.'/'; 
preg_match($ftwo,$input, $display);
print_r($display[1]);

$ftwo='/'.$f11.'(.*?)'.$f12.'/';

preg_match($ftwo,$input,$display);
print_r($display[1]);

?>

所以这里我有显示数据[1] ...我如何将它传递给我的api?

修改

为什么这不起作用?

$url="***"
//Pass to api

$optional_headers=null;
$params = array('http' => array(
              'method' => 'POST',
              'content' => $data
            ));
  if ($optional_headers !== null) {
    $params['http']['header'] = $optional_headers;
  }
  $ctx = stream_context_create($params);
  $fp = @fopen($url, 'rb', false, $ctx);
  if (!$fp) {
    throw new Exception("Problem with $url, $php_errormsg");
  }
  $response = @stream_get_contents($fp);
  if ($response === false) {
    throw new Exception("Problem reading data from $url, $php_errormsg");
  }

1 个答案:

答案 0 :(得分:1)

在PHP中使用cURL(http://php.net/manual/en/book.curl.php)。 这样的事情可以解决问题:

//add the variables to the var below
$url=" http://******/********{YOUR_PARTNER_ID}&AuthKey={YOUR_API_KEY}&******Name={Name}&*****MobileNo={Phone‌​number}&*******=&******=&****=&*****=&T****=*****&Mode=****";

//curl stuff 
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$return = curl_exec ($ch);
curl_close ($ch);

请注意,必须在服务器上启用cURL。