简体   繁体   English

从PHP脚本返回JSON

[英]Return JSON from PHP script

I know that there is many content from this kind of topic but it's quite strange what's happening in my case. 我知道这种主题有很多内容,但是对于我而言,这很奇怪。

The fact is that this was working without problems and suddenly it does not return anything. 事实是,这没有问题,并且突然不返回任何内容。 $data and $postsInCat has the desired content but when echoed, the received response is empty. $data$postsInCat具有所需的内容,但是在回显时,收到的响应为空。

Here is the code: 这是代码:

<?php
header('Content-Type: application/json');
include "wp-blog-header.php";
mb_internal_encoding("UTF-8");

$paged = (get_query_var('page')) ? get_query_var('page') : 1;
$temp = $wp_query;
$wp_query= null;
$args = array(
              'posts_per_page' => 20,
              'post_type'      => 'post',
              'paged'          => $paged,
              'nopaging'       => false,
              'cat'            => $_GET['author']
);
$wp_query = new WP_Query($args);

$data = array();
while ($wp_query->have_posts()) : $wp_query->the_post();
    $obj = new stdClass;
    $obj->id              = $post->ID;
    $obj->title           = $post->post_title;
    $obj->excerpt         = substr(strip_tags($post->post_content), 0, 250).'...';
    $obj->slug            = str_replace('http://187.38.230.170/', '', get_permalink($post->ID));
    $obj->author_name     = get_user_by('id', $post->post_author)->user_login;
    $obj->featured_image  = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'post-thumbnails') );
    $obj->date            = new DateTime($post->post_date);
    $obj->date            = $obj->date->format("F d, Y");

    array_push($data, $obj);
endwhile;

$postsInCat = get_term_by('id', $_GET['author'], 'category');
echo json_encode(array('data' => $data, 'n_resultados' => $postsInCat->count));
?>

If I print $data with print_r function, it prints the whole content. 如果我使用print_r函数打印$data ,它将打印整个内容。

Any idea what's happening? 知道发生了什么事吗?

Check the JSON Errors using json_last_error() . 使用json_last_error()检查JSON错误。 Possibly there's a character which cannot be put inside JSON. 可能有一个字符不能放在JSON中。 I encountered a same issue and I used this code: 我遇到了相同的问题,并且使用了以下代码:

<?php
    function utf8ize($d) {
        if (is_array($d)) {
            foreach ($d as $k => $v) {
                $d[$k] = utf8ize($v);
            }
        } else if (is_string ($d)) {
            return utf8_encode($d);
        }
        return $d;
    }
?>

You can make something like: 您可以进行如下操作:

$array = utf8ize($array);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM