PHP:如何使用Array中的PHP解码给定的String

时间:2015-12-28 11:21:54

标签: php json

响应字符串:

jQuery21408111137825120874_1451285646793({"result":"error","msg":"0 - This email address looks fake or invalid. Please enter a real email address."})

此响应由API提供。我在最后使用PHP。我不确定给定的响应是否在JSON中,但我已经厌倦了json_decode但没有成功。请帮我如何以数组格式解码它。

3 个答案:

答案 0 :(得分:2)

您也可以使用     $ encodeArr = json_decode($ yourString,true);

你得到一个数组结果..

或者你可以使用     $ encodeArr = json_decode($ yourString);     $味精= $ encodeArr-> MSG; 这也可行

答案 1 :(得分:1)

试试这个:

<form action="" method= "POST">
    First name: <input type="text" name="data_name"><br>
    E-mail: <input type="email" name="data_mail"><br>
    City: <input type="text" name="data_city"><br>
    <input type="submit" value="Submit">
</form>

<?php

    $dsn = 'mysql:host=localhost;dbname=tabelaDB';
    $username = 'root';
    $password = 'pass';

    $db = new PDO($dsn, $username, $password);

    $name = $_POST['data_name'];
    $mail = $_POST['data_mail'];
    $city = $_POST['data_city'];

    $sql = $db->prepare( "INSERT INTO data ( data_name, data_mail, data_city ) VALUES ( :data_name, :data_mail, :data_city )");

    $sql->bindValue(':data_name', $name);
    $sql->bindValue(':data_mail', $mail);
    $sql->bindValue(':data_city', $city);

    $sql->execute();
?>

结果是(对象格式):

$string = 'jQuery21408111137825120874_1451285646793({"result":"error","msg":"0 - This email address looks fake or invalid. Please enter a real email address."})';

preg_match('#\(({.*?})\)#', $string, $match); // this will return the value inside the {}
$yourString = $match[1];
$encodeArr = json_decode($yourString);
echo "<pre>";
print_r($encodeArr);

如果要将此对象转换为stdClass Object ( [result] => error [msg] => 0 - This email address looks fake or invalid. Please enter a real email address. ) ,请在打印前使用此对象:

array

结果是:

$requiredArr = (array) $encodeArr;
print_r($encodeArr);

答案 2 :(得分:0)

json_decode的第二个参数PHP函数用于将json转换为数组PHP。如果它是一个有效的json,你可以有一个数组PHP对象,否则你的json是无效的。

查看:json_decode PHP function