我试图解析mysql中的文章,并使用php在json中编码数据.
目前我发表的文章使用:
<?php if ($success): ?>
<?php foreach($article->get_items() as $item): ?>
<?php echo $item->get_content(); ?>
<?php endforeach; ?>
<?php endif; ?>
Run Code Online (Sandbox Code Playgroud)
而我正在尝试将其编码为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; ?>
Run Code Online (Sandbox Code Playgroud)
另外,我不确定如何使用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"}}
]
Run Code Online (Sandbox Code Playgroud)
因为我没有正确使用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"}
]
Run Code Online (Sandbox Code Playgroud)
而且内容有时它包含破坏json编码的html元素,所以我想我必须把它编码成json或string?
And*_*er2 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);
}
Run Code Online (Sandbox Code Playgroud)
<?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));
?>
Run Code Online (Sandbox Code Playgroud)
实际上,我不确定我是否了解您的需求,因此可能无济于事。