12

Solr returns response in following JSON format.

{
  "responseHeader":{
    "status":0,
    "QTime":2,
    "params":{
      "indent":"on",
      "start":"0",
      "q":"*:*",
      "wt":"json",
      "version":"2.2",
      "rows":"10"}},
  "response":{"numFound":3,"start":0,"docs":[
      {
        "student_id":"AB1001",
        "student_name":[
          "John"]
    },
      {
        "student_id":"AB1002",
        "student_name":[
          "Joe"]
    },
      {
        "student_id":"AB1003",
        "student_name":[
          "Lorem"]
    }]

  }}

What will be the simple way to read student_id, student_name using PHP?

Aadi
  • 6,959
  • 28
  • 100
  • 145

5 Answers5

18

Use $obj = json_decode($yourJSONString); to convert it to an object.

Then use foreach($obj->response->docs as $doc) to iterate over the "docs".

You can then access the fields using $doc->student_id and $doc->student_name[0].

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
10

PHP has a json_decode function that will allow you to turn a JSON string into an array:

$array = json_decode($json_string, true);
$student_id = $array['response']['docs'][0]['student_id'];
...

Of course, you might want to iterate through the list of students instead of accessing index 0.

honeyp0t
  • 837
  • 8
  • 15
2
$result = json_decode($result, true);
$result['response']['docs'][0]['student_id'] ...
deceze
  • 510,633
  • 85
  • 743
  • 889
0
$json_a = json_decode($string, TRUE);
$json_o = json_decode($string);


#array method
foreach($json_a['response']['docs'] as $students)
{
    echo $students['student_id']." name is ".$students['student_name'][0];
    echo "<br>";
}

#Object Method`enter code here`
foreach($json_o->response->docs as $sthudent_o)
{
    echo $sthudent_o->student_id. " name is ".$sthudent_o->student_name[0];
    echo "<br>";
}
0

Why not just use one of the PHP clients for Solr, or the PHP response writer? See http://wiki.apache.org/solr/SolPHP

Mauricio Scheffer
  • 98,863
  • 23
  • 192
  • 275