I am trying to parse articles from mysql and encode the data in json with php.
Currently publishing articles I use:
<?php if ($success): ?>
<?php foreach($article->get_items() as $item): ?>
<?php echo $item->get_content(); ?>
<?php endforeach; ?>
<?php endif; ?>
and I am trying to encode this into json.
I have tried this:
<?php if ($success): ?>
<?php foreach($feed->get_items() as $item): ?>
<?php
$data = array(
'id' => "1",
'result' => array(
'title' => 'This is the title',
'publish' => 'John Doe',
'content' => $item->get_content()
)
);
echo json_encode($data);
?>
<?php endforeach; ?>
<?php endif; ?>
Also, I'm not sure how I would use foreach() so that I could parse and encode all the content.
UPDATE:
The content parsed from $item->get_content() has HTML elements such as , etc. so they should be encoded into json or strings ?
UPDATE 2:
The problem is that currently I end up with this:
[
{"id":"1","result":{"title":"This is the title","publish":"John Doe","content":"content 1"}},
{"id":"1","result":{"title":"This is the title","publish":"John Doe","content":"content 1"}},
{"id":"1","result":{"title":"This is the title","publish":"John Doe","content":"content 1"}},
{"id":"1","result":{"title":"This is the title","publish":"John Doe","content":"content 1"}},
{"id":"1","result":{"title":"This is the title","publish":"John Doe","content":"content 1"}}
]
because I am not using foreach() properly and I want to end up with this:
[
{"id":"1","result": {"title":"This is the title","publish":"John Doe","content":"content 1"},
{"title":"This is the title","publish":"John Doe","content":"content 1"},
{"title":"This is the title","publish":"John Doe","content":"content 1"},
{"title":"This is the title","publish":"John Doe","content":"content 1"},
{"title":"This is the title","publish":"John Doe","content":"content 1"}
]
and also the content sometimes it contains html elements which destroys the json encoding so I would imagine I have to encode it into json or string?
echo
incontent
's value and you should be fine. – Interrobang Mar 28 '13 at 22:42<?php
unless you have to. Here, you definitely do not want to. – Eric Mar 28 '13 at 22:43