1

I am having a challenge correctly parsing an array in PHP. Here is the output of the array:

[{"address":"2801 Elliott Ave","category_ids":[347],"category_labels":[["Social","Food and 
Dining","Restaurants"]],"country":"us","email":"[email protected]","factual_id":"43cfe23
8-ae8e-469a-8592-a1edc8603051","fax":"(206) 448-
9252","latitude":47.615154,"locality":"Seattle","longitude":-122.353724,"name":"The Old 
Spaghetti Factory","neighborhood":["Belltown","Downtown","Downtown 
Seattle"],"postcode":"98121","region":"WA","tel":"(206) 441-
7724","website":"http:\/\/www.osf.com"}]

And here is the parsing attempt...

$mark = array("[");
$mark2 = array("]");
$replacemark  = array("");
$array = str_replace($mark, $replacemark, $array);
$array = str_replace($mark2, $replacemark, $array);
$array = stripslashes($array);

$obj = json_decode($array);

$address = $obj->{'address'};
$country = $obj->{'country'};
$factual_id = $obj->{'factual_id'};
$latitude = $obj->{'latitude'};
$locality = $obj->{'locality'};
$longitude = $obj->{'longitude'};
$name = $obj->{'name'};
$postcode = $obj->{'postcode'};
$region = $obj->{'region'};
$status = $obj->{'status'};
$tel = $obj->{'tel'};

Any ideas why these values are not returning anything? Thanks!

1
  • 1
    What is all the replacing atop supposed to accomplish? Commented Oct 22, 2013 at 1:27

2 Answers 2

1

There's no need to strip the square brackets. Simply call json_decode() on the data and retrieve your information.

Note: the data in the form you have it decodes to an array of objects, with just one object, so you need to provide an array subscript:

$json = json_decode("My JSON Data...here");
echo $json[0]->address;

See this fiddle

2nd Note: the data as you have posted it has embedded newlines which caused a problem with json_decode(). If you have those in your original data you'll need to strip them before decoding. I edited them out in the fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

You don't need to remove the square brackets in the JSON string, and then try accessing your values like $obj->address

Edit:

That JSON string returns an array with your object at index 0, tested myself, so to access your values you will need to: $obj[0]->address or set your object $obj = $de_json[0]; and accessing values as I said above

2 Comments

json_decode() is returning NULL with and without the brackets
works fine for me, only problem is that the JSON string when decoded returns an array containing the object at index 0 so the above needs some adjusting

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.