2
I would like to generate a JSON file for my site to display the latest news at the top to another third site!
2
I would like to generate a JSON file for my site to display the latest news at the top to another third site!
7
If the site is not of 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 that way
PHP
echo json_encode("teste");
Upshot
{"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 in an array and later print using json_encode
Fictitious 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);
Upshot
[{"title":"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""}]
And the treatment 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 recovered with a $.get
or $.post
and will be treated in the place that should be on the site.
Browser other questions tagged php javascript json
You are not signed in. Login or sign up in order to post.
Be more detail, please, I don’t understand what you want?
– Fernando Leal
@Rodrido, so got very wide. Generate a JSON file from a select? from a webservice call? try to specify a little more your problem, to oblige your question to be closed as too wide
– Caputo
What is "new news", do you already have the SQL query? What is "at the top"? Why did you use the Javascript tag? Please check out the [Ask] tab and [Edit]and the question to add details. If you want more clarification in the answer already given, add the details and leave a comment in the reply "clarified such thing, check the update".
– brasofilo