代码之家  ›  专栏  ›  技术社区  ›  Mario

从HTML源代码中提取JSON并使用它

  •  0
  • Mario  · 技术社区  · 8 年前

    我有一个类似的网址 http://example.com -它的HTML源代码是:

    <html>
    test
    test2
    {"customer":{"email":null,"is_eu":true"}
    t
    </html>
    

    我只想从中得到JSON,然后从这个JSON中得到任何东西。

    我的当前代码在这里:

    $whole_html = htmlspecialchars(file_get_contents("http:/example.com"));
    preg_match('~\{(?:[^{}]|(?R))*\}~', $whole_html, $json);
    $JsonResults = print_r($json, true);
    $json_decoded = json_decode($JsonResults, true);
    echo $json_decoded['customer']['email'];
    

    但结果是空页。

    编辑 :结果 echo print_r($json, true) 是:

    Array ( [0] => {"customer":{"email":null,"is_eu":true} )
    

    任何帮助都将不胜感激。

    谢谢!

    1 回复  |  直到 8 年前
        1
  •  1
  •   Meskan    8 年前

    上面HTML代码示例中的JSON字符串不正确。一定是这样的

    “customer”:“email”:空,“is_eu”:真

    您可以使用以下代码。

    $whole_html = file_get_contents("http:/example.com");
    preg_match('~\{(?:[^{}]|(?R))*\}~', $whole_html, $json);
    $arr = json_decode($json[0],true);
    $email = $arr['customer']['email']; 
    $is_eu = $arr['customer']['is_eu'];