duanchangnie7996
2018-05-28 18:21
浏览 91
已采纳

从HTML源中提取JSON并使用它

I have a URL like http://example.com - The HTML source of it is:

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

I want to get the JSON only from it then get anything from this JSON

My current code is here:

$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'];

But the result is empty page.

EDIT: The result of echo print_r($json, true) is:

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

Any help would be appreciated.

Thanks!

图片转代码服务由CSDN问答提供 功能建议

我有一个像 http://example.com - 它的HTML源代码为:

 &lt; html&gt; 
test 
test2 
 {“customer”:{  “email”:null,“is_eu”:true“} 
t 
&lt; / html&gt; 
   
 
 

我想从中获取JSON然后获取任何内容 来自这个JSON

我当前的代码在这里:

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

但结果是空页 。

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

  Array([0] =&gt; {“customer”:{“email”:null,“is_eu”:true})
   \  n 
 

任何帮助将不胜感激。

谢谢!

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dream04110 2018-05-28 19:14
    已采纳

    The json string in the example html code above is incorrect. It must be like this

    {"customer":{"email":null,"is_eu":true}}

    You can use the following code.

    $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']; 
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题