【问题标题】:Laravel - htmlspecialchars() expects parameter 1 to be string, object givenLaravel - htmlspecialchars() 期望参数 1 是字符串,给定对象
【发布时间】:2017-08-30 06:45:55
【问题描述】:

我出现这个错误:

htmlspecialchars() expects parameter 1 to be string, object given

我在控制器中使用:

$data = '{"pr":{"code":"1"},"ac":[[{"icon":"web","action":"link","url":"asd"}]]}'
$newData = json_decode($data);

我将它作为数组发送到视图:'data' => $newData 当我尝试在视图中使用 $data 时,它给了我这个错误

已经尝试使用 $data->ac OR $data['ac'] 但还是一样... 请帮忙?

【问题讨论】:

  • 可以添加视图的代码吗?
  • {{ $data }} => 就是这样。
  • json_decode 默认返回一个对象。对数组使用$newData = json_decode($data,TRUE);
  • htmlspecialchars() 期望参数 1 是字符串,给定数组

标签: php laravel


【解决方案1】:

当您使用刀片回显{{ $data }} 时,它会自动转义输出。它只能转义字符串。在您的数据中,$data->ac 是一个数组,$data 是一个对象,两者都不能按原样回显。您需要更具体地说明数据的输出方式。究竟是什么样子完全取决于您要完成的工作。例如,要显示链接,您需要执行{{ $data->ac[0][0]['url'] }}(不知道为什么您有两个嵌套数组,但我只是按照您的数据结构)。

@foreach($data->ac['0'] as $link)
    <a href="{{ $link['url'] }}">This is a link</a>
@endforeach

【讨论】:

  • 工作就像一个魅力。谢谢。
  • 我有这个是因为$errors-&gt;get() 正在返回一个数组。切换到$errors-&gt;first() 解决了这个问题。
【解决方案2】:

如果您真正的意图是将整个数组从 html 发送到控制器,您可以使用以下代码:

来自blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 

在控制器中

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or
    
    return view('quotation')->with('quotation',json_decode($req->quotation))


}

【讨论】:

    【解决方案3】:

    你可以使用serialize

    <input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">
    

    但在这种情况下,最好的方法是在刀片中使用 json_encode 方法,在控制器中使用 json_decode

    【讨论】:

      【解决方案4】:

      这是在 laravel 中访问数据的正确方法:

      @foreach($data-> ac as $link) 
      
         {{$link->url}}
      
      @endforeach
      

      【讨论】:

        【解决方案5】:

        尝试在您的收藏中使用json_encode()

        https://www.php.net/manual/pt_BR/function.json-encode.php

        public static function getTeamMemberInto($user_id){
            
            $team = DB::table('members_team')
                        ->join('teams', 'teams.id', '=', 'members_team.teams_id')
                        ->join('employees', 'employees.id', '=', 'teams.leader_employees_id')
                        ->where('members_team.employees_id', '=', $user_id)
                        ->select('*')->first();
            // dd($team);
            if($team){
                return json_encode($team, true);
            }else{
                return false;
            }
                                
        }
        

        【讨论】:

          猜你喜欢
          • 2018-07-30
          • 2021-02-13
          • 2020-11-22
          • 1970-01-01
          • 2023-04-09
          • 2018-02-22
          • 2018-11-10
          • 2017-08-08
          • 2017-07-12
          相关资源
          最近更新 更多