Can a JSON object returned by PHP contain a date object

前端 未结 5 666
轻奢々
轻奢々 2020-12-20 11:36

Is there a way to create a JSON object in PHP that contains a javascript date object? Does json_encode automatically convert PHP\'s DateTime<

5条回答
  •  孤城傲影
    2020-12-20 12:40

    While I agree with @postfuturist answer, there is an alternative: regular expression with syntactic sugar.

    $json_data = json_encode(['test' => '__' . $_SERVER['REQUEST_TIME']]);
    
    $json_data = preg_replace_callback('/"__([0-9]{10})"/u', function ($e) {
        return 'new Date(' . ($e[1] * 1000) . ')';
    }, $json_data);
    

    Which would produce:

    string(32) "{"test":new Date(1385820141000)}"
    

    or

    Object {test: Sat Nov 30 2013 14:02:21 GMT+0000 (GMT)}
    

    if JSON data was to be handled in JavaScript.

    This would cover most of the use cases (note that UNIX timestamp is not necessarily 10 characters long). If used in production, more syntactic sugar should be used to prevent accidental replacement of the value.

    This should be used only when JSON is injected at the page load time, rather than via XHR, e.g.

    
    
    
    
    
    
    
    

提交回复
热议问题