Apalabrados Apalabrados - 1 year ago 79
JSON Question

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.

has the desired content but when echoed, the received response is empty.

Here is the code:

header('Content-Type: application/json');
include "wp-blog-header.php";

$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('', '', 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);

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

If I print
function, it prints the whole content.

Any idea what's happening?

Answer Source

Check the JSON Errors using json_last_error(). Possibly there's a character which cannot be put inside JSON. I encountered a same issue and I used this code:

    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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download