我正在尝试从 mysql 解析文章并使用 php 将 json 中的数据编码。
目前发表的文章我使用:
<?php if ($success): ?>
<?php foreach($article->get_items() as $item): ?>
<?php echo $item->get_content(); ?>
<?php endforeach; ?>
<?php endif; ?>
我正在尝试将其编码为 json。
我试过这个:
<?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; ?>
另外,我不确定如何使用 foreach()来解析和编码所有内容。
更新:
从$item->get_content()解析的内容具有 HTML 元素,例如,等等,所以它们应该被编码成 json 或字符串?
更新 2:
问题是目前我最终得到了这个:
[
{"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"}}
]
因为我没有正确使用 foreach()并且我想以这个结束:
[
{"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"}
]
而且内容有时包含破坏json编码的html元素,所以我想我必须将它编码为json或字符串?