>我有一个php文件列表.php
<?php
$arr=array('444','555');
echo var_export($arr);
?>
现在我想使用 file_get_contents 从另一个 php 脚本获取数组。如何实现这一点?我不想使用会话。这两个脚本位于不同的服务器上。
您可以serialize()
数组或使用json_encode()
以 JSON 格式对数组进行编码。然后,在其他 PHP 脚本中,您将使用 unserialize()
或 json_decode()
将字符串重新放入数组中。
例如,使用 serialize()
:
在 a.php 中(在服务器 A 上)
$array = array( "foo" => 5, "bar" => "baz");
file_put_contents( 'array.txt', serialize( $array));
在 b.php 中(在服务器 B 上)
$string = file_get_contents( 'http://www.otherserver.com/array.txt');
$array = unserialize( $string);
var_dump( $array); // This will print the original array
您也可以从 PHP 脚本输出字符串,而不是将其保存到文件中,如下所示:
在 a.php 中(在服务器 A 上)
$array = array( "foo" => 5, "bar" => "baz");
echo serialize( $array); exit;
在 b.php 中(在服务器 B 上)
$string = file_get_contents( 'http://www.otherserver.com/a.php');
$array = unserialize( $string);
var_dump( $array); // This will print the original array
作为nickb答案的一点延伸:
脚本1
$arr=array('444','555');
file_put_contents("data.txt", serialize($arr));
脚本 2
$arr = unserialize(file_get_contents("data.txt"));
应该工作!
编辑:哦,好吧,尼克自己添加了一个例子:)