【问题标题】:Read JSON file?读取 JSON 文件?
【发布时间】:2013-08-16 22:00:57
【问题描述】:

所以我想用 PHP 搜索一个 JSON 文件。 json 链接:http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json。我只是将 JSON 文件放在我的网络服务器中。这是我的脚本:

<?php
    $query = $_GET['s'];

    $terms =  explode(' ', $query);
    $results = array();

    foreach(file('items.json') as $line) {
        $found = true;

        foreach($terms as $term) {
            if(strpos($line, $term) == false) {
                $found = false;
                break;
            }
        }

        if($found) {
            $results[] = $line;
        } else {

        }
    }
    print_r($results);

问题是它显示了整个 json 文件而不是我的 $query。我能做些什么来解决这个问题?

【问题讨论】:

  • [json_decode](php.net/json_decode] 可能是你要找的。试试json_decode(file_get_contents("items.json"), true);
  • 不,只是一堆错误
  • 您打算搜索哪些数据?
  • @Timmy6118CP 你能指出错误吗?
  • 警告:file() 期望参数 1 是有效路径,数组在第 8 行的 C:\xampp\htdocs\Programs\Test\index.php 中给出警告:为 foreach( ) 在第 8 行的 C:\xampp\htdocs\Programs\Test\index.php 中

标签: php json parsing


【解决方案1】:

您可以使用json_encodearray_filter 和闭包 (PHP 5.3+) 来完成此操作。

$obj = json_decode(file_get_contents("http://media1.clubpenguin.com/play/en/web_service/game_configs/paper_items.json"), true);

$termStr = "ninja kiwi";
$terms = explode(" ", $termStr);

$results = array_filter($obj, function ($x) use ($terms){
    foreach($terms as $term){
        if (stripos($x["label"], $term) ||
            stripos($x["paper_item_id"], $term))
        {
            return true;
        }
    }
    return false;
});

echo json_encode($results);

【讨论】:

  • 感谢 OrangePill!有什么办法可以将 print_r 更改为 echo 吗?我做到了,但我得到了错误:第 18 行的 C:\xampp\htdocs\Programs\Test\index.php 中的数组到字符串转换
  • @Timmy6118CP 你想把 json 打印回来吗?如果是这样,只需将 print_r($results); 更改为 echo json_encode($results);
  • @Timmy6118CP,真的吗?也许你应该雇人。
  • @Orangepill 我以前试过。只是回显 json 文件
  • 如果你能展示一个你想从这个过程中得到什么的例子,也许会有所帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-03-18
  • 2014-03-31
  • 1970-01-01
  • 1970-01-01
  • 2021-02-25
  • 2022-11-27
  • 2011-10-28
相关资源
最近更新 更多