嗨,大家好,如果我从Web服务获得json文件,那是在我的html中显示它的最好方法。我应该使用php来显示内容还是ajax。如果是php,我该怎么做。
这是我的json文件的示例
{
"results": [
{
"title": "Brick Mansions",
"released": "2014",
"restricted": "12 \u00e1ra",
"imdb": "6.0\/10 5,532 atkv.",
"imdbLink": "http:\/\/www.imdb.com\/title\/tt1430612",
"image": "http:\/\/kvikmyndir.is\/images\/poster\/9260_500.jpg",
"showtimes": [
{
"theater": "Laugar\u00e1sb\u00ed\u00f3",
"schedule": [
"20:00",
"22:00"
]
}
]
},
{
"title": "How to Train your Dragon 2",
内容位于名为$ movies的数组中,如您在我的php文件中所见
<?php
$service_url ='http://apis.is/cinema';
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
if ($curl_response === false) {
$info = curl_getinfo($curl);
die('Error occured during curl exec:'. var_export($info));
}
curl_close($curl);
//get file and insert it into json file
$movies = json_encode(json_decode($curl_response), JSON_PRETTY_PRINT);
file_put_contents('json/data.json', $movies);
?>
我一直试图像这样放入我的index.php页面,但没有任何运气。这可能很容易,但是我是后端新手。
这是我的index.php文件
<body>
<?php include 'php/response.php';?>
<?php echo "$movies"; ?>
<div class="container">
<div class="movies" style="background-color:green;">
<?php if (is_array($movies)): ?>
<?php foreach($movies as $movie): ?>
<?php echo $movie['title']; ?>
<?php endforeach ?>
<?php endif; ?>
</div>
</div>
如您所见,我的数组$ movie打印在页面上,但是我似乎无法仅打印标题,依此类推。提前致谢。
尝试将json文件转换为PHP可以理解的内容,即数组。
同样,<?php.. ?>
如果您有多行代码,也无需将每一行PHP换行,只需将其用于打开解释器一次,然后将其关闭即可。这将使您的代码更易于阅读和调试。
<body>
<?php include 'php/response.php';?>
<?php
echo "$movies"; // this echos a text string
$movys = json_decode($movies); // convert json string to an object
?>
<div class="container">
<div class="movies" style="background-color:green;">
<?php
if (is_array($movys->results)):
foreach($movys->results as $movie):
echo $movie->title;
endforeach;
endif;
?>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句