【问题标题】:display json file in html with php ajax or php使用 php ajax 或 php 在 html 中显示 json 文件
【发布时间】:2014-06-22 15:42:30
【问题描述】:

大家好,如果我从 webservice 获得了 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 打印但我似乎不能只打印标题等。提前致谢。

【问题讨论】:

  • 为什么只能打印title - 其他数组元素有什么问题?你为什么要这样做:echo "$movies";?
  • 不,关键是我无法打印标题,而 echo $movies 只是显示 json 内容的测试。我希望只能显示例如图像的标题等

标签: php jquery ajax json


【解决方案1】:

尝试将 json 文件转换为 PHP 可以理解的内容,即数组。

此外,如果您有不止一行代码,则无需将每一行 PHP 行包装在 &lt;?php.. ?&gt; 中,只需使用一次打开解释器,一次关闭它。它将使您的代码更易于阅读和调试。

<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>

【讨论】:

  • 好的,我会试试,让你知道
  • 不,它没有工作,但无论如何感谢任何其他想法?
  • 帮我一个忙,在$movys = json_decode($movies);之后做一个print_r($movys)
  • 我想我明白了,我改变了答案
  • 是的,我做到了,但它给了我一个致命错误:不能在第 24 行的 C:\wamp\www\Movies\frontpage.php 中使用 stdClass 类型的对象作为数组
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 2016-01-28
相关资源
最近更新 更多