【问题标题】:PHP Array to JSON with json_encode didnt work带有 json_encode 的 PHP 数组到 JSON 不起作用
【发布时间】:2018-09-06 11:04:11
【问题描述】:

但找不到解决方案。

所以我有一个如下所示的数组:

Array(
[0] => Array
    (
        [ID] => 1
        [Vorname] => Fisrtname
        [Nachname] => Lastname
        [Geburtsdatum] => 1990-01-01
        [Email] => test@testmail.com
        [Telefon] => 0511123123
    ))

我想将其转换为 JSON 并将其用作 Slim 的响应。

问题在于,那个 echo json_encode();并返回 $response->withJson();什么都不返回。

正如我所说,我搜索了很多,这两种方法是我能找到的。也许你知道为什么这不起作用。

【问题讨论】:

  • 您使用的确切代码是什么?
  • @ArtisticPhoenix 感谢这个提示。我收到了这条消息:格式错误的 UTF-8 字符,可能编码不正确
  • 遍历数组并修复它,$item = mb_convert_encoding($item, "UTF-8", "UTF-8")
  • 我们不能说 `$response->withJson();` 是什么或做什么,因为你没有告诉我们。但我们当然可以说 json_encode() 在使用数组作为参数调用时确实工作。

标签: php json slim php-7


【解决方案1】:

回复:json_last_error_msg()

格式错误的 UTF-8 字符,可能编码不正确

这是一个常见的问题。

function utf8convert($mixed, $key = null)
{
    if (is_array($mixed)) {
        foreach ($mixed as $key => $value) {
            $mixed[$key] = utf8convert($value, $key); //recursive
        }
    } elseif (is_string($mixed)) {
        $fixed = mb_convert_encoding($mixed, "UTF-8", "UTF-8");
        return $fixed;
    }
    return $mixed;
}

这几乎就像我只是从我之前写的东西中复制了这段代码......大声笑......这让我在过去很头疼。所以,有没有做过。

【讨论】:

  • 必须删除 $this->,因为这是我用于 Json Encoding 的一个类,它会自动解决一些错误,所以我为你实现了它。
  • 我使用 PDO 来获取数组。所以另一种方式是:'mysql:host='。 $这个->主机。 ';dbname=' 。 $this->dbname 。 ";charset=utf8"
  • 我试过了,但我忘记了为什么我在原始版本中将其注释掉了……哈哈。所以我现在不记得为什么了,但我确定我是有原因的。见//$fixed = utf8_encode();也许只是更快,我们处理数十亿行数据,所以我总是比较速度。老实说,我不记得了……
  • 也许是Windows-1252mb_ 转换了...Please note that utf8_encode only converts a string encoded in ISO-8859-1 to UTF-8 无论如何我尝试过并决定不使用它...
  • @Adrian - 如果它是一个数据库源(在我的情况下是 CSV 文件)作为 JSON 放入队列系统,那将是首选方式。
【解决方案2】:
<?php
$arr=[
  [
    'ID'           => 1,
    'Vorname'      => 'Fisrtname',
    'Nachname'     => 'Lastname',
    'Geburtsdatum' => '1990-01-01',
    'Email'        => 'test@testmail.com',
    'Telefon'      => '0511123123'
  ]
];
echo json_encode($arr);
?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-13
    • 2012-07-28
    相关资源
    最近更新 更多