1

我正在尝试从 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或字符串?

4

3 回答 3

12

创建一个包含所有数据的数组,然后将其编码为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);
}
于 2013-03-28T22:48:39.910 回答
5
<?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));
?>

实际上,我不确定我是否了解您的需求,因此可能无济于事。

于 2013-03-28T22:47:38.513 回答
2

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

echo htmlspecialchars(json_encode($data));

例如:

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

echo htmlspecialchars(json_encode($data));

// Outputs: {"id":"<hello>"}
于 2013-03-28T23:04:40.050 回答