API 在 HTML 中返回 JSON。正常吗?

API returning a JSON in an HTML. Is it normal?

我有一个项目,我必须处理在线营销平台提供的 API 以注册用户和其他典型(此处不相关)操作。

今天他们给我发了 API 文件,我很困惑,因为它字面意思是 "... 它 returns 一个 HTML returns 一个 JSON..."。它显示了一个这样的例子:

<html> 
<head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <meta name="XX:pagetag" content="" /> 
    <meta name="XX:flowtag" content="" /> 
</head> 
<body leftmargin='0' rightmargin='0' topmargin='0' bottommargin='0' bgcolor='#FFFFFF'> 
    <RESULT>[{ &quot;userid&quot;: 1, &quot;status&quot;: &quot;OK&quot; }]</RESULT> 
</body> 
</html> 

所以我有两个问题:

  1. 为什么会有人构建一个 API 以这种方式响应? 这对我来说真的没有意义。这比只返回 JSON 和正确的 JSON headers 有什么好处?也许我错过了什么...

  2. 使用 PHP,这是解析此响应并获得实际 JSON? 我读过的最佳方式SO 中的多个 answers 和评论不鼓励使用正则表达式来解析 HTML 但到目前为止,这是我能想到的唯一方法。我试过:

    // This will be a CURL call:
    $response = file_get_contents('./example-response.html');
    
    $regexp = '/<RESULT>(.*)<\/RESULT>/';
    $matches = [];
    preg_match($regexp, $response, $matches);
    print_r($matches);
    

顺便说一句,此代码在我的 MAMP 服务器中不起作用,但在 https://www.functions-online.com/preg_match.html 中却有效…

任何建议将不胜感激。谢谢!

  1. 你完全正确,这看起来很疯狂。
  2. 你可以使用PHP's SimpleXMLElement,它是xpath-method来解析HTML。也不要忘记对那些 htmlentities 进行转义 :)