如何使用json_encode?

时间:2016-06-29 06:23:57

标签: php json

此代码正常运行,但我需要使用 json_encode

<?php
    require_once('person_class.php');
    $person = new Person_class();

    $first_name = addslashes ($_POST['first_name']);
    $last_name = addslashes ($_POST['last_name']);
    $birthday = addslashes ($_POST['birthday']);
    $gender = addslashes ($_POST['gender']);

    $person_id = $person->addPerson($first_name, $last_name, $birthday, $gender);

    echo "
        {   \"status\"      : \"1\",
            \"error\"       : \"0\",
            \"person_id\"   : \"$person_id\",
            \"first_name\"  : \"$first_name\",
            \"last_name\"   : \"$last_name\",
            \"birthday\"    : \"$birthday\",
            \"gender\"      : \"$gender\"
        }";
?>

我想更改此部分并使用json_encode

回声&#34;             {\&#34; status \&#34; :\&#34; 1 \&#34;,                 \&#34;错误\&#34; :\&#34; 0 \&#34;,                 \&#34;为person_id \&#34; :\&#34; $ person_id \&#34;,                 \&#34;如first_name \&#34; :\&#34; $ first_name \&#34;,                 \&#34;姓氏\&#34; :\&#34; $ last_name \&#34;,                 \&#34;生日\&#34; :\&#34; $ birthday \&#34;,                 \&#34;性别\&#34; :\&#34; $ gender \&#34;             }&#34 ;;

2 个答案:

答案 0 :(得分:1)

对于<?php include "emails/PHPMailer/PHPMailerAutoload.php"; //Create a new PHPMailer instance $mail = new PHPMailer(); $mail->IsSMTP(); $mail->SMTPDebug = 1; $mail->SMTPAuth = true; $mail->SMTPSecure = 'ssl'; $mail->Host = "smtp.gmail.com"; $mail->Port = 465; $mail->IsHTML(true); //Username to use for SMTP authentication $mail->Username = "@gmail.com"; $mail->Password = ""; //Set who the message is to be sent from $mail->setFrom('mzubim@gmail.com', 'Zubair Mushtaq'); //Set an alternative reply-to address $mail->addReplyTo('replyto@gmail.com', 'Secure Developer'); //Set who the message is to be sent to $mail->addAddress('abulogics@gmail.com', 'Abulogicss'); //Set the subject line $mail->Subject = 'PHPMailer SMTP test'; //Read an HTML message body from an external file, convert referenced images to embedded, //convert HTML into a basic plain-text alternative body $mail->msgHTML("convert HTML into a basic plain-text alternative body"); //Replace the plain text body with one created manually $mail->AltBody = 'This is a plain-text message body'; //send the message, check for errors if (!$mail->send()) { echo "Mailer Error: " . $mail->ErrorInfo; } else { echo "Message sent!"; } 函数,您需要先创建一个数组,然后在函数中传递数组。 例如,

json_encode

有关详细信息,请参阅Here

在您的代码中,我找不到您要创建的任何要使用的数组<?php $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); echo json_encode($arr); ?> 。例如,代码示例json_encode变量不清楚它是普通变量还是数组。

答案 1 :(得分:-1)

我需要使用post值构建一个json字符串,然后将post值保存在数组中,如

    $data=array();
        $data['first_name'] = $_POST['first_name'];
        $data['last_name'] = $_POST['last_name'];
        $data['birthday'] = $_POST['birthday'];
        $data['gender'] = $_POST['gender'];

echo json_encode($data);

会给你一个json字符串