您可以使用file_get_contents() 或php cURL。 cURL 参考如下:
首先,在您的网站 A 上添加一个api.php。
api.php
<?php
if($_REQUEST['key'] != '555')
{
$final = array('error' => 'Invalid Key');
echo json_encode($final);
exit();
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_a";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$action = $_REQUEST['action'];
//update, del, get by id, get all
switch($action)
{
case 'get_all':
$sql = 'SELECT * FROM tbl_a';
$rs = mysqli_query($conn,$sql);
$final = array();
while($row = mysqli_fetch_assoc($rs))
{
$final[] = $row;
}
echo json_encode($final);
break;
default:
$final = array('error' => 'Invalid Command');
echo json_encode($final);
}
?>
接下来,在您的网站 B 中添加以下代码。
<?php
$cSession = curl_init();
curl_setopt($cSession,CURLOPT_URL,"http://yoursite.com/api.php?key=555&action=get_all");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result=curl_exec($cSession);
curl_close($cSession);
$arr = json_decode($result);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>
您可能会变得更安全,或者可能会以您的方式对其进行调整,添加更多功能来插入、删除、通过 id 获取,但这是基本思想。希望能帮助到你。 :)