0

Below is the starting of json that I've received in $json variable.

{"page":"0","cartaddonpopover":{"refreshfeature":1,"featurehtml":""},"initiateid":null,"containsmapitem":0,"wishlist":{"refreshfeature":1,"featurehtml":"\n<div id=\"cart-wishlist\" style=\"display:none;\" class=\"cart-wish-list\"  >\n</div>\n\n"},"gutter":{"refreshfeature":1,"featurehtml":"\n\n\n\n\n\n\n    \n    \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n<div id=\"cart-gutter\" class=cart-gutter quantity=\"151\">\n\n  

I want to extract the value of quantity, which is 151 in above case.

I'm currently using, $quantity = $json->featurehtml->{"cart-gutter"}->quantity; and I know that I'm wrong. Please guide.

Barmar
  • 741,623
  • 53
  • 500
  • 612
Lavneet
  • 516
  • 5
  • 19

3 Answers3

3

Try this:

$html = str_get_html(json_decode($json)->featurehtml);
$quantity = $html->find("#cart-gutter")->quantity;
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • hey, str_get_html is not working in my case. Can you suggest any alternate ? – Lavneet Mar 20 '14 at 12:52
  • 1
    There are a number of ways to process HTML in PHP, but I'm not really familiar with them. They're in the Programming PHP book. – Barmar Mar 20 '14 at 12:54
  • For $html = str_get_html($json->featurehtml); , I'm getting, Notice: Trying to get property of non-object. – Lavneet Mar 20 '14 at 13:07
  • I assumed that `$json` was the result of calling `json_decode()` on that JSON string. Was I wrong? – Barmar Mar 20 '14 at 13:09
  • No. I didn't decoded the json. The json i presented was encoded. – Lavneet Mar 20 '14 at 13:12
  • If you didn't decode it, why did you have `$json->featurehtml` in the question? Anyway, I added the call to json_decode to my answer. – Barmar Mar 20 '14 at 13:46
1

You can always use a regexp to do this.

preg_match('/quantity=\\\"(\d+)\\\"/', $json, $matches);
$quantity = $matches[1];
Alexis
  • 66
  • 2
-1

have you tried this.

$array = json_decode($json, true);
echo $array['quantity'];
Abhishek
  • 517
  • 3
  • 18
  • Take a closer look at his JSON. Quantity is not a property, it's an attribute of an HTML element. – Barmar Mar 20 '14 at 12:52