PHP如何将查询字符串分成变量

时间:2015-12-01 23:39:44

标签: php mysql string paypal

我有一个paypal表单,提交自定义隐藏输入的值。由于我要解析一些额外的数据,我已将它们添加为查询字符串。即。

<input type="hidden" name="custom" value="payment-type=deposit&user-id=<?php echo $user_id; ?>&user-name=<?php echo $user_name; ?>">

输出为:

<input type="hidden" name="custom" value="payment-type=deposit&user-id=1&user-name=admin">

然后我有一个名为paypal-ipn.php的文件,它与paypal进行通信,并将支付数据添加到我的数据库中。我使用$ _POST方法得到每个输入的值,即

$item_name        = $_POST['item_name']; // wedding name
$booking_id       = $_POST['item_number']; // booking id
$payment_status   = $_POST['payment_status']; // payment status
$payment_amount   = $_POST['mc_gross']; // amount?
$payment_currency = $_POST['mc_currency']; // currency
$txn_id           = $_POST['txn_id']; // transaction id
$receiver_email   = $_POST['receiver_email']; // reciever email i.e. your email
$payer_email      = $_POST['payer_email']; // payer email i.e. client email
$custom_variables = $_POST['custom'];

最后一个将(希望)返回我的查询字符串。我的问题是,如何将查询字符串分成单独的变量,即

$payment_type = PAYMENT TYPE FROM STRING
$user_id = USER ID FROM STRING
$user_name = USER NAME FROM STRING

有没有办法用php做到这一点?

以下是我根据以下答案尝试的最新代码:

$custom_variables = $_POST['custom'];

parse_str($custom_variables);
echo $payment_type;  
echo $user_id; 
echo $user_name; 

parse_str($str, $output);
$payment_type = $output['payment_type'];
$user_id = $output['user_id'];
$user_name = $output['user_name'];

2 个答案:

答案 0 :(得分:1)

使用解析字符串

  

解析str,好像它是通过URL传递的查询字符串,并在当前范围内设置变量。

<?php
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first;  // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz

parse_str($str, $output);
echo $output['first'];  // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz

?>

http://php.net/manual/en/function.parse-str.php

更新

parse_str($custom_variables , $output);
$payment_type = $output['payment_type'];
$user_id = $output['user_id'];
$user_name = $output['user_name'];

echo $payment_type;  
echo $user_id; 
echo $user_name; 

答案 1 :(得分:0)

您可以这样做:

$string = "payment-type=deposit&user-id=1&user-name=admin";

parse_str($string, $output);
echo $output['payment-type'];
echo $output['user-id'];
echo $output['user-name'];

//Output
deposit1admin