在PHP中搜索json文件的文件内容并返回结果

时间:2016-05-22 15:34:45

标签: php json search

我正在尝试在php中创建一个搜索函数,该函数搜索Json文件中包含的数据。我能够为普通文本文件执行此操作,该文件根据在返回壁橱匹配的搜索字段中输入的内容返回结果列表。但是,对于json文件执行此操作时不起作用,并且不返回任何内容。

search.php

if (isset($_POST) && isset($_POST['txt'])) {

    $search = $_POST['txt'];
    $file = file('data/contacts.json');
    $found = false;

    $jsonData = json_decode($file, true);

    foreach ($jsonData as $line) {
        if (strpos($line, $search) !== false) {
            $found = true;
            echo $line;
        }
    }
    if (!$found) {
        echo 'No match found';
    }
}

contacts.json

[
    {
    "id": 3,
    "forename": "John",
    "surname": "Smith",
    "email": "j@hotmail.com",
    "address": "addresss",
    "telephone": "01232302323"
},
{
    "id": 4,
    "forename": "Keith",
    "surname": "Miller",
    "email": "K@hotmail.com",
    "address": "ssdsds",
    "telephone": "01232302323"
},
{
    "id": 5,
    "forename": "Doug",
    "surname": "Howard",
    "email": "d@hotmail.com",
    "address": "test",
    "telephone": "01232302323"
},
{
    "id": 2,
    "forename": "r",
    "surname": "r",
    "email": "email@gmail.com",
    "address": "test",
    "telephone": "01232302323"
}

 ]

1 个答案:

答案 0 :(得分:0)

将此行$jsonData = json_decode($file, true);更改为

$jsonData = json_decode(json_encode($file),true);