How to generate a json file with the new news to display on my site? [closed]

1

I would like to generate a JSON file for my site to display the latest news on top for another third party site!

    
asked by anonymous 02.07.2014 / 22:12

1 answer

6

If the site is not from the same domain you will need to use this code at the top of the file.

PHP

header('Access-Control-Allow-Origin: *'); //Qualquer site
header('Access-Control-Allow-Origin: http://site.com'); //Especificar os sites

To return in Json would look like this

PHP

echo json_encode("teste");

Result

  

{"test"}

To generate a file

PHP

$string = "minha string";
$fp = fopen('arquivo.json', 'w');
fwrite($fp, json_encode($string));
fclose($fp);

For your news you should bring your news and structure into an array and then print using json_encode

Fictional example of an array with the news:

PHP

$noticias = array(
array(
    "titulo" => "noticia 1",
    "corpo" => "corpo da noticia 1",
    "data" => "02/07/2014"
    ),

array(
    "titulo" => "noticia 2",
    "corpo" => "corpo da noticia 2",
    "data" => "02/07/2014"
),

array(
    "titulo" => "noticia 3",
    "corpo" => "corpo da noticia 3",
    "data" => "02/07/2014"
),

array(
    "titulo" => "noticia 4",
    "corpo" => "corpo da noticia 4",
    "data" => "02/07/2014"
)
);

echo json_encode($noticias);

Result

  

["title": "news 1", "body": "body of news 1", "date": "02/07/2014"}, {"title": "news 2" "body of the news 2", "date": "02/07/2014"}, {"title": "news 3", "body" "Body": "body of news 4", "date": "02/07/2014"}]

And the handling of this Json can be done with Jquery

Jquery

$(function(){
    var jsonString = [{"titulo":"noticia 1","corpo":"corpo da noticia 1","data":"02\/07\/2014"},{"titulo":"noticia 2","corpo":"corpo da noticia 2","data":"02\/07\/2014"},{"titulo":"noticia 3","corpo":"corpo da noticia 3","data":"02\/07\/2014"},{"titulo":"noticia 4","corpo":"corpo da noticia 4","data":"02\/07\/2014"}];

    $.each(jsonString, function(i, item){
        $('.noticias').append("<li>"+ item.data +" - " +item.titulo + "</li>");
    });
});

Obviously this json would be retrieved with a $.get or $.post and will be treated in the place that should be on the site.

DEMO - Jquery

    
02.07.2014 / 22:30