【问题标题】:Converting string to json object or array in php在php中将字符串转换为json对象或数组
【发布时间】:2016-06-03 02:22:20
【问题描述】:

我必须做一个网络服务。因此我参考了网上的一些教程并想出了以下代码

index.php

<html>
<head>
    <title>Form page</title>
</head>

<body>

    <form action="http://localhost:81/my%20web%20service/webservice" method="get">
        Table name:<br>
        <input type="text" name="s" value=""><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

webservice.php

<?php

    include('connectdb.php');

    $something = $_GET['s'];
    $sqlcode = mysql_query("Select * from $something");

    $jsonObj= array();
    while($result=mysql_fetch_object($sqlcode))
    {
        $jsonObj[] = $result;
    }

    $final_res =json_encode($jsonObj) ;
    echo $final_res;
?>

connectdb.php

<?php
    $hostname="localhost";
    $username="root"; //write your username
    $password=""; //write your password
    $db_name="webservice_trial"; //write your db name
    $con=mysql_connect($hostname,$username,$password);
    mysql_select_db($db_name,$con) or die ("Cannot connect the Database");
    mysql_query("SET NAMES 'utf8'",$con); 

?>

上面的代码工作正常。 当我从 form.php 输入一个表的名称时,它将检索该特定表中的所有元组。

现在我想做的是让数据显示在另一个页面上。 即我想将数据从 webservice.php 从 json 格式传输到另一个页面。所以我编辑了我的 webservice.php 如下

webservice.php

<?php

    include('connectdb.php');

    $something = $_GET['s'];
    $sqlcode = mysql_query("Select * from $something");

    $jsonObj= array();
    while($result=mysql_fetch_object($sqlcode))
    {
        $jsonObj[] = $result;
    }

    $final_res =json_encode($jsonObj) ;
    echo $final_res;

    $jsonArray = (array) json_decode($final_res);
    echo $jsonArray[0];

?>

它给出了以下错误

[{"name":"hilton","town":"colombo","telephone":"774933705","description":"excellent"},{"name":"galadari","town":"colombo","telephone":"112894143","description":"best"},{"name":"mt. lavinia","town":"mt. lavinia","telephone":"773580324","description":"good"}]

可捕获的致命错误:第 18 行的 C:\xampp\htdocs\json_folder\my web service\webservice.php 中的类 stdClass 的对象无法转换为字符串

【问题讨论】:

  • 错字jsonArray,需要$
  • 发布代码的最后一行。 jsonArray 前面需要一个 $。
  • 您还需要解决发布的代码中存在的 SQL 注入问题。 :)
  • 我编辑了错字,但它仍然给出错误。帮帮我

标签: php json string web


【解决方案1】:

你可以改变

$jsonArray = json_decode($final_res);

$jsonArray = json_decode($final_res, True);  

或者,要访问第一个项目的名称,请使用

print $jsonArray[0]->name;

【讨论】:

    【解决方案2】:

    不要尝试将解码后的字符串类型转换为数组,而是使用 this,这是正确的方法。

    $jsonArray = json_decode($final_res, TRUE);
    

    现在,您将拥有一个数组,您可以使用echovar_dump

    var_dump($jsonArray);
    

    正如你的问题,你的错误说的是,你试图将echo它作为一个变量,你试图回显的实际上是一个对象类。可能是因为它没有被类型转换。

    建议:

    • 请停止使用mysql 函数。它已弃用。使用mysqliPDO

    • 了解 SQL 注入。永远不要相信用户输入。始终清理它们或使用准备好的语句。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-29
      • 2011-05-21
      • 1970-01-01
      • 1970-01-01
      • 2020-12-19
      相关资源
      最近更新 更多