【问题标题】:How to extract value from a below json using php如何使用php从下面的json中提取值
【发布时间】:2014-04-27 07:43:40
【问题描述】:

下面是我在 $json 变量中收到的 json 的开头。

{"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  

我想提取quantity的值,在上面的例子中是151

我目前正在使用$quantity = $json-&gt;featurehtml-&gt;{"cart-gutter"}-&gt;quantity;,我知道我错了。请指导。

【问题讨论】:

  • 你能发帖print_r($json);吗?
  • json 是否总是完全相同的结构?如果是这样,json_decode 和一些正则表达式应该可以帮助你。
  • @TheWolf:是的。 json 将始终具有相同的结构。请提出一些答案。
  • 使用 json_decode() 然后在这里发布结果。我瘦 json_decode 会有所帮助
  • 数量不是 JSON 组件的值,它是 featurehtml 属性中的 HTML 元素的属性。您需要使用 HTML DOM 解析器。

标签: php json


【解决方案1】:

试试这个:

$html = str_get_html(json_decode($json)->featurehtml);
$quantity = $html->find("#cart-gutter")->quantity;

【讨论】:

  • 嘿,str_get_html 在我的情况下不起作用。你能推荐任何替代品吗?
  • 在 PHP 中有多种处理 HTML 的方法,但我对它们不是很熟悉。它们在 PHP 编程一书中。
  • 对于 $html = str_get_html($json->featurehtml); ,我明白了,注意:试图获取非对象的属性。
  • 我假设 $json 是在那个 JSON 字符串上调用 json_decode() 的结果。我错了吗?
  • 没有。我没有解码json。我呈现的 json 是编码过的。
【解决方案2】:

您始终可以使用正则表达式来执行此操作。

preg_match('/quantity=\\\"(\d+)\\\"/', $json, $matches);
$quantity = $matches[1];

【讨论】:

    【解决方案3】:

    你试过了吗?

    $array = json_decode($json, true);
    echo $array['quantity'];
    

    【讨论】:

    • 仔细看看他的 JSON。数量不是属性,它是 HTML 元素的属性。
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多