PHP:json_encode-使用foreach()并为json编码html元素


PHP: json_encode - Using foreach() and encoding html elements for json

我正在尝试从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"}
]

还有内容,有时它包含html元素,这会破坏json编码,所以我想我必须将其编码为json或字符串?

创建一个保存所有数据的数组,然后将其编码为json

if ($success){
    $result = array();
    foreach($feed->get_items() as $item){
        $data = array(
             'id'    =>    "1",
             'result'       =>    array(
                   'title'    =>   'This is the title',
                   'publish'  =>  'John Doe',
                   'content'  =>  $item->get_content()
             )
         );
         array_push($result,$data);
    }                
    echo json_encode($result);
}
<?php
foreach($article->get_items() as $item){
    $result[] = array(
            'title'   => 'This is the title',
            'publish' => 'John Doe',
            'content' => $item->get_content()
        );
    );
}
echo json_encode(array('id'=>'1', 'result'=>$result));
?>

事实上,我不确定我是否理解你需要什么,所以也许这不会有帮助。

输出包含HTML代码的字符串时,您需要使用htmlspecialchars:

echo htmlspecialchars(json_encode($data));

例如:

$data = array('id' => '<hello>');
echo htmlspecialchars(json_encode($data));
// Outputs: {"id":"<hello>"}