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

时间:2013-03-28 22:41:03

标签: php api 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-&gt; 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或string?

3 个答案:

答案 0 :(得分:10)

创建一个包含所有数据的数组,然后将其编码为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);
}

答案 1 :(得分:4)

<?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));
?>

其实我不确定我理解你需要什么,所以也许没用。

答案 2 :(得分:2)

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

echo htmlspecialchars(json_encode($data));

例如:

$data = array('id' => '<hello>');

echo htmlspecialchars(json_encode($data));

// Outputs: {"id":"<hello>"}