【问题标题】:Parsing either JSON or atom+xml response not working (PHP)解析 JSON 或 atom+xml 响应不起作用 (PHP)
【发布时间】:2014-07-20 14:45:07
【问题描述】:

我将 CURL 与一个 API (OData) 一起使用,该 API (OData) 以 JSON 或 ATOM+XML 格式返回数据(这是此 API 的两个选项,可以在 CURLOPT_HTTPHEADER 设置中设置)。这是我的代码:

$url = "https://www.mywebsite.com/4.3/TableExample()?".'$filter'."=(IDNumber%20eq%20'115735')%20and%20(StatusID%20eq%202)%20and%20(AnotherID%20eq%207)%20and%20(IDDate%20ge%20datetime'2012-10-24T00:00:00')%20and%20(IDDate%20le%20datetime'2015-10-26T00:00:00')".'&$expand'."=Items";

$curlConn = curl_init($url); 
curl_setopt($curlConn,CURLOPT_HTTPHEADER,array('Accept: application/atom+xml')); 

//OR FOR JSON
//curl_setopt($curlConn,CURLOPT_HTTPHEADER,array('Accept: application/json')); 

$ret = curl_exec($curlConn); 
curl_close($curlConn);

这很好用(事实上,这段代码单独在浏览器中显示响应信息而无需回显等)。

当我得到 atom+xml 返回时,它会在浏览器中返回它,如下所示:

<!--?xml version="1.0" encoding="utf-8" standalone="yes"?-->
<html>
    <head></head>
    <body>
        <feed xml:base="http://www.mywebsite.com/4.3/" xmlns:d="http://schemas.microsoft.com/ado/2007/08/dataservices" xmlns:m="http://schemas.microsoft.com/ado/2007/08/dataservices/metadata" xmlns="http://www.w3.org/2005/Atom">
            <title type="text">TableExample</title>
            <id>http://www.mywebsite.com/4.3/TableExample</id>
            <updated>2014-05-30T18:37:34Z</updated>
            <entry>
                 <!--DATA RETURNED HERE-->
            </entry>

然后是结束标签。这很奇怪,因为它不完全是 XML,也不完全是 HTML。此外,当我尝试使用 SimpleXMLElement 解析它时,它什么也找不到。我也尝试过 simplexml_load_string 但这不起作用。当我以 JSON 格式收到它时,它看起来像普通的 JSON 代码,但又被包裹在 HTML 标记中,所以我假设这就是 json_decode 在元素上不起作用的原因。

任何想法为什么我无法解析这些数据?

【问题讨论】:

  • 当您使用simplxml_load_string 时,您在日志中看到任何错误吗?当您在结果对象上使用 print_r 时会发生什么?即$x = simplexml_load_string($atomstring); print_r($x);
  • 嗨@Robbert,当我这样做时,我得到一个错误:Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '&lt;' not found in 然后是文件和行号信息...
  • 提要是您创建的吗?奇怪的是 JSON 代码被包裹在 html 标签中。那不应该发生。如果您创建了提要,我会在那里查看您的代码,以确保您发送正确编码的 JSON 和 XML。
  • 不,我不创建提要。我只是从我向其发送参数的 API 中提取它们。

标签: php xml json curl


【解决方案1】:

我可以通过将 CURLOPT_RETURNTRANSFER 值添加到请求中来完成这项工作:

curl_setopt($curlConn,CURLOPT_RETURNTRANSFER,1); 

对于 JSON 标头,我使用了 json_decode 并将其设为数组。并且在 header 中使用 atom+xml,我使用 new SimpleXMLElement() 将其转换为数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-17
    • 2013-04-24
    • 2016-09-03
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多