php 响应内容必须是实现 __toString()、\"boolean\" 的字符串或对象。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26022390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 18:06:37  来源:igfitidea点击:

The Response content must be a string or object implementing __toString(), \"boolean\" given."

phplaravellaravel-4

提问by Alen

I'm trying to return a rendered View using Response::jsonbut I'm getting this error:

我正在尝试使用返回呈现的视图,Response::json但出现此错误:

The Response content must be a string or object implementing __toString(), \"boolean\" given."

This is my code:

这是我的代码:

$posts = Post::where( ... )->orderBy( ... )->get();
$data['posts'] = View::make("posts.partials.loadHome")->with("posts", $posts)->render();
$data['msg'] = "ok";

return Response::json($data);

If I var_dump($data)I get this:

如果var_dump($data)我得到这个:

<pre class='xdebug-var-dump' dir='ltr'>
<b>array</b> <i>(size=2)</i>
  'posts' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'&lt;div class=&quot;post postGrid&quot; data-id=&quot;1864&quot;&gt;&#10; &lt;a target=&#39;_blank&#39; href=&quot;http://objavi.net/posts/1864&quot;&gt;&lt;img src=&quot;http://objavi.net/&quot; id=&quot;imgWrap&quot; data-original=&quot;/thumbs/YAo4wFzIpl76.jpg&quot; class=&quot;lazy&quot; alt=&quot;Deset manje poznatih ?injenica o Jozefu Staljinu&quot;&gt;&lt;/a&gt;&#10;  &#10;   &lt;div id=&quot;bodyPreview&quot;&gt;&#10;     &#10;       &lt;a target=&#39;_blank&#39; href=&quot;http://objavi.net/posts/1864&quot;&gt;&lt;h1 class=&quot;previewTitle&quot;&gt;Deset manje poznatih ?injenica o Jozefu Staljinu&lt;/h1&gt;&lt;/a&gt;&#10;&#10;     &lt;h3 id=&quot;postInfo&quot;&gt;&#10;                         &lt;a class=&quot;paint&quot; href=&quot;/category/17&quot;&gt;zanimljivosti&lt;/a&gt;&#10; '...</font> <i>(length=12172)</i>
  'msg' <font color='#888a85'>=&gt;</font> <small>string</small> <font color='#cc0000'>'ok'</font> <i>(length=2)</i>
</pre>

This is posts.partials.loadHomeview:

这是posts.partials.loadHome视图:

@foreach($posts as $post)

<div class="post postGrid" data-id="{{ $post->id }}">
    <a target='_blank' href="{{ URL::action('PostsController@show', $post->id) }}">{{ HTML::image(null, $post->title, ["id" => "imgWrap", "data-original" => $post->getThumb(), "class" => "lazy"]) }}</a>

    <div id="bodyPreview">

        <a target='_blank' href="{{ URL::action('PostsController@show', $post->id) }}"><h1 class="previewTitle">{{ e($post->title) }}</h1></a>

        <h3 id="postInfo">
            @foreach($post->categories as $c)
                <a class="paint" href="/category/{{ $c->id }}">{{ $c->name }}</a>
            @endforeach
        </h3>

        <h2 class="bodyPreview">{{ strip_tags(truncString($post->body, 160)) }}</h2>

        <div id="createdBy">
            <a href="{{ URL::action('UsersController@show', $post->user()->first()->id) }}">
                {{ HTML::image($post->user()->first()->getAvatar(), $post->user()->first()->username, ["width" => "32", "height" => "32"]) }}

                {{{ $post->user()->first()->username }}}
            </a>
            <label id="timeAgo">{{ localDate($post->created_at); }}</label>
        </div>
    </div>
</div>
@endforeach

I tested this on localhost and everything works fine. What could be the problem?

我在本地主机上对此进行了测试,一切正常。可能是什么问题呢?

回答by user2778080

Check to make sure there aren't any illegal characters. I had this issue once and ran utf8_encode on the string and that solved the issue.

检查以确保没有任何非法字符。我曾经遇到过这个问题并在字符串上运行 utf8_encode 并解决了这个问题。

回答by WillyBurb

I ran in to this blog postand think it gives a pretty good idea for fixing it:

我看到了这篇博客文章,并认为它提供了一个修复它的好主意:

This kind of error will kill you if yo are going to debug it Or trace it step by step, you will never find the solution because this error happens in response, I mean that it will be detected by the framework only after the response is ready to be rendered ,So it is as the message said "the response is boolean". Often it will happen in the view that some variables affect the response content . Just check the view variables one by one ,and remove each of them the try to run again . you will find the variable that cause this error. But before going in this path try to change the view by any other view page (blade-template) and see if the error is still there . if it is not , then the problem in the view page.

如果您要调试它或逐步跟踪它,这种错误会杀死您,您将永远找不到解决方案,因为此错误发生在响应中,我的意思是只有在响应准备好后框架才会检测到它被渲染,所以正如消息所说的“响应是布尔值”。在视图中经常会发生一些变量影响响应内容的情况。只需一一检查视图变量,并删除它们中的每一个,然后再次尝试运行。您将找到导致此错误的变量。但是在进入此路径之前,请尝试通过任何其他视图页面(刀片模板)更改视图并查看错误是否仍然存在。如果不是,则是视图页面中的问题。

回答by Juan Manuel Garcia Carmona

Create the following function

创建以下函数

function utf8_encode_deep(&$input) {
    if (is_string($input)) {
        $input = utf8_encode($input);
    } else if (is_array($input)) {
        foreach ($input as &$value) {
            self::utf8_encode_deep($value);
        }

        unset($value);
    } else if (is_object($input)) {
        $vars = array_keys(get_object_vars($input));

        foreach ($vars as $var) {
            self::utf8_encode_deep($input->$var);
        }
    }
}

Try to do the following

尝试执行以下操作

utf8_encode_deep($data);
return Response::json($data);

回答by toesslab

In my case the error

在我的情况下,错误

the Response content must be a string or object implementing __toString(), "boolean" given.

响应内容必须是实现 __toString() 的字符串或对象,给出“布尔值”。

apeared also even when eliminating view variables one by one or when using another view (as suggsested by WillyBurb). So his answer was not working for me.

即使在一个一个地消除视图变量或使用另一个视图(如 WillyBurb 所建议的)时,也出现了。所以他的回答对我不起作用。

After a long research I found out that the problem was caused by the following columns:

经过长时间的研究,我发现问题是由以下列引起的:

  • created_at
  • updated_at
  • deleted_at.
  • created_at
  • updated_at
  • deleted_at.

After adding them to the $hiddenproperty, the error was gone.

将它们添加到$hidden属性后,错误消失了。

from the docs:

从文档:

Hiding Attributes From Array Or JSON Conversion

Sometimes you may wish to limit the attributes that are included in your model's array or JSON form, such as passwords. To do so, add a hidden property definition to your model:

从数组或 JSON 转换中隐藏属性

有时您可能希望限制包含在模型数组或 JSON 格式中的属性,例如密码。为此,请向模型添加隐藏属性定义:

class User extends Eloquent {
    //...
    protected $hidden = array(
        'password',
        'remember_token',
        'deleted_at',
        'created_at',
        'updated_at'
    );
    //...
}

回答by Elminson De Oleo Baez

You can try this please? im return true or false (a boolean value) and not an Response value like this

你可以试试这个吗?我返回真或假(布尔值)而不是像这样的响应值

return Response::json(array(
        'error' => false,
        'message' => 'Valid Pincode'),
        200
    );

回答by u6244725

first :

第一的 :

this error only happened when you return false;

这个错误只发生在你 return false;

it means Response::json($data) == false.

这意味着 Response::json($data) == false

second :

第二 :

some character that json can't encode

某些 json 无法编码的字符

perhaps,some ASCII char (like 0x00~0x31that can't display) in your string...

也许,0x00~0x31你的字符串中有一些 ASCII 字符(比如不能显示)...

so,json encode return false

所以,json 编码返回 false

回答by Arjen

Although this question is a bit old and your problem probably solved by now, I thought this may be relevant for others. Tl;dr:use DB::statement("SET NAMES 'UTF8'");just before retrieving the results from the database.

虽然这个问题有点老了,你的问题现在可能已经解决了,但我认为这可能与其他人有关。Tl; dr:DB::statement("SET NAMES 'UTF8'");在从数据库中检索结果之前使用。

Your data is probably stored in a character set other than UTF-8 in the database, for instance lantin1. As an alternative for encoding the DB results in your application, you might consider letting the DB handle this.

您的数据可能以 UTF-8 以外的字符集存储在数据库中,例如 lantin1。作为在应用程序中对 DB 结果进行编码的替代方法,您可以考虑让 DB 处理此问题。

When using MySQL, you can specify the character set to communicate to the server with using SET NAMES 'charset_name'. This specifies to the server that queries are sent using this character set, and asks the server to return results using this character set. (see documentation)

使用 MySQL 时,您可以使用SET NAMES 'charset_name'. 这向服务器指定使用此字符集发送查询,并要求服务器使用此字符集返回结果。(见文档

Laravel expects UTF-8 data. So, in this case you can issue a statement asking to communicate in UTF-8 before selecting results:

Laravel 需要 UTF-8 数据。因此,在这种情况下,您可以在选择结果之前发出要求以 UTF-8 进行通信的声明:

DB::statement("SET NAMES 'UTF8'");
$posts = Post::where( ... )->orderBy( ... )->get();

If necessary, you can always switch back to another character set afterwards.

如有必要,您可以随时切换回另一个字符集。

回答by Rápli András

That you didn't create $data = array();and the local and remote PHP versions differ.

您没有创建$data = array();并且本地和远程 PHP 版本不同。