0

How do I parse this JSON with PHP?

[{"index":0,"date":" 20120029","title":"testtitle"}

There are multiple instances of this. for example:

[{"index":0,"date":" 20120029","title":"testtitle"},{"index":1,"date":" 20120007","title":"testtitle"},{"index":2,"date":" 20120006","title":"testtitle"}]

When I try an online parser i get this.

[
{
"index":0,
"date":" 20120029",
"title":"testtitle"
},
{
"index":1,
"date":" 20120007",
"title":"testtitle"
},
{
 "index":2,
 "date":" 20120006",
 "title":"testtitle"
}
]

What i need to know is how would i extract the data and get a variable for $index, $date, $title??

I need this within a foreach. So for every event echo it out?

Any help would be great.

Thanks

4 Answers 4

1

Try

$data = '[{"index":0,"date":" 20120029","title":"testtitle"},{"index":1,"date":" 20120007","title":"testtitle"},{"index":2,"date":" 20120006","title":"testtitle"}]';

$json = json_decode($data);
foreach($json as $v)
{
    echo $v->index;
    echo $v->date;
    echo $v->title;
}
Sign up to request clarification or add additional context in comments.

Comments

1

In PHP you can use json_decode to convert the data back into an array/object (PHP docu). For the actual traversal I would prefer a usual for loop here.

$data = json_decode( '[{"index":0,"date":" 20120029","title":"testtitle"},{"index":1,"date":" 20120007","title":"testtitle"},{"index":2,"date":" 20120006","title":"testtitle"}]', true );

for( $i=0; $i<count($data); $i++ ) {
  echo $data[ $i ][ 'index' ];
  echo $data[ $i ][ 'date' ];
  echo $data[ $i ][ 'title' ];
}

But if you want to use a foreach loop:

foreach( $data as $item ) {
  echo $item[ 'index' ];
  echo $item[ 'date' ];
  echo $item[ 'title' ];
}

1 Comment

You forgot to pass the $assoc parameter to json_decode ... either that or you should use -> :)
0

You use json_decode() for that.

foreach (json_decode($str, true) as $item) {
    echo $item['title'], "\n";
}

Comments

0

Why don't you try josn_decode()?

$myNewArrayMadeFromJSON = json_decode($jsonString);

for () {
 // A loop over $myNewArrayMadeFromJSON
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.