Slim JSON Outputs

前端 未结 17 1664
一整个雨季
一整个雨季 2021-01-30 09:00

I am using the Slim framework with PHP to create a RESTful API for my app. However, I assumed that the framework would have some way of creating easier JSON outputs rather than

相关标签:
17条回答
  • 2021-01-30 09:38
    function _die($array){
       echo json_encode($array);
       exit;
    }
    
    
    $result = mysql_query("SELECT * FROM table");
    while($row = mysql_fetch_assoc($result)){
        $array[] = $row;
    }
    
    _die($array);
    
    0 讨论(0)
  • 2021-01-30 09:38

    header("Content-Type : application/json"); echo json_encode($data);

    0 讨论(0)
  • 2021-01-30 09:41
    header("Content-Type: application/json");
    echo json_encode($result);
    exit;
    

    Hint: Using The Slim PHP Framework for Developing REST APIs

    0 讨论(0)
  • 2021-01-30 09:42

    Using Slim 3, I'm using this format:

    <?php
    
    $app = new \Slim\App();
    
    $app->get('/{id}', function ($request, $response, $args) {
        $id = $request->getAttribute('id');
    
        return $response->withJSON(
            ['id' => $id],
            200,
            JSON_UNESCAPED_UNICODE
        );
    });
    

    On request "/123", result JSON with:

    {
      id: "123"
    }
    

    More infos read here.

    [UPDATE] Added second and third param to withJSON. Second is The HTTP status code, and third is Json encoding options (best for especial chars and others, for example: print "ã" correctly)

    0 讨论(0)
  • 2021-01-30 09:44

    I think Slim also provides a middleware object which does this automatically so users of that framework doesnt have to write json_decode and encode on every request, its called the Slim_Middleware_ContentType object.

    $app->response()->('application/json');
    $app->add(new Slim_Middleware_ContentType());
    

    it does the decoding for you. the decoding works great.But for encoding the last post is great.

    Thanks, Dharani

    0 讨论(0)
  • 2021-01-30 09:45

    My fix was adding "exit;" at the end of the json print out, my dev server didn't care, but my live server would not trigger the json end event. I did not need to add headers or use json_encode.

    0 讨论(0)
提交回复
热议问题