我有一些PHP全局变量使用问题。我从StackOverflow搜索,但没有什么像我的(至少我没有找到)。
我有2个php页面。 Index.php和Account.php 。 Index.php通过ajax调用account.php。 Account.php必须从其他URL接收一些xml数据并存储它。之后,Index.php必须使用它。
index.php上的:
$("#login-submit").click(function(){
$("#span-login-loading").css('visibility','visible');
var dataString = 'user='+ $("#login-name").val() + '&pass=' + $("#login-pass").val();
$.ajax({
type: "POST",
url: "pages/account.php",
data: dataString,
success: function(data) {
$("#login-form").html(data);
$("#span-login-loading").css('visibility','hidden');
if (data.substr(0, 12) == "Logged in as"){
$("#div-login-submit").html('<a href="pages/account.php?logout=1" id="logout">Гарах</a>');
}
}
});
return false;
});
on account.php:
$xml_data = "<loginRequest>
<username>" . $_POST['user'] . "</username>
<password>" . $_POST['pass'] . "</password>
</loginRequest>";
$url = "url here";
$username = "name here";
$password = "pass here";
$process = curl_init($url);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_TIMEOUT, 10);
curl_setopt($process, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($process, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_HTTPHEADER, array('Content-Type: text/xml'));
curl_setopt($process, CURLOPT_POSTFIELDS, $xml_data);
$return = curl_exec($process);
$info = curl_getinfo($process);
$xml = simplexml_load_string($return);
curl_close($process);
如何将$ xml传递给index.php?我的问题更像是“如何在会话中存储xml类型对象”。因为目前我使用会话来存储数据。但是在字符串数据的情况下,它可以在下面的行中工作:
$_SESSION['user_name'] = (string)$xml->request->username;
如果我从中删除(字符串),则会出现错误,如致命错误:在第0行的“未知”中没有堆栈帧的情况下抛出异常,但我需要传递对象,而不是字符串。
答案 0 :(得分:1)
$xml = simplexml_load_string($return);
echo $xml; // add this line at the end of account.php
curl_close($process);
此外 - 当您想从其他php页面中获取$ xml的内容时,您可以通过获取accounts.php的已处理页面来填充变量
$xml = file_get_contents('http://yourserver.com/pages/account.php');
将内容转换为xml对象:
$xml = simplexml_load_string(file_get_contents('http://yourserver.com/pages/account.php'));
答案 1 :(得分:1)
快速解决方案应该通过序列化:您可以将xml对象保存到这样的会话中:
$_SESSION['whatever']=$xml->asXML();
并将其检索为
$xml = simplexml_load_string($_SESSION['wathever']);
注意:强> 序列化是对该术语的不当使用,因为simplexml没有实现可序列化的接口,我可以从文档中看到,因此我们必须序列化它 依靠simplexml提供的函数