2011-12-27 18 views
-1

我试图检索使用curl使用此代码从一个API数据:使用数据

$xml_data = '<name>foobar%</name>'; 

$URL = "http://www.example.com/api/foobar.xml"; 

$ch = curl_init($URL); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data"); 
$output = curl_exec($ch); 
curl_close($ch); 

当我执行这个PHP脚本,一切运作良好,并返回正确的XML数据在我的浏览器中。我的问题是,我如何解析这些数据?

(如果你建议我做使用不同的方法,卷曲,整个事情,请随时告诉我)

+0

参见[PHP的最佳XML分析器(http://stackoverflow.com/q/188414/693207)查看解析器列表。 – 2011-12-27 09:52:42

回答

0

检查PHP docs for curl_exec function - 请注意,除非启用CURLOPT_RETURNTRANSFER,否则返回值将为真/假,在这种情况下,它将是调用的结果。

这里有一个更新的例子,将返回在$output的数据,并通过curl_getinfo()获得转让的细节:

$xml_data = 'foobar%'; 

$URL = "http://www.example.com/api/foobar.xml"; 

$ch = curl_init($URL); 
curl_setopt($ch, CURLOPT_POST, 1); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); 
curl_setopt($ch, CURLOPT_POSTFIELDS, "$xml_data"); 
$output = curl_exec($ch); 
$info = curl_getinfo($ch); 
curl_close($ch); 

print_r($info); 
print_r($output);
+0

似乎是错误的谢谢你!这工作得很好,正是我所期待的 – 2011-12-30 23:39:05

0

你可以使用simplexml解析它

+0

好的,但我应该分析哪个$变量或URL? – 2011-12-27 10:23:58

+0

解析你的$输出变量 – 2011-12-27 10:25:59

+0

我试过用simplexml,但它不起作用。 $输出似乎是一个布尔值(用gettype测试它)。我该怎么办? – 2011-12-27 10:38:05

1

您可以使用下面样的代码。

$xml = simplexml_load_string($output); 

如果你需要通过它的节点,你可以简单地通过下面的例子给出的那些。

例:

$imageFileName = $xml->Cover->Filename; 

如果你需要,你可以使用XPath为好。 例如:

$nodes = $xml->xpath(sprintf('/lfm/images/image/sizes/size[@name="%s"]', 'extralarge')); 

祝你好运!

Prasad。

+0

谢谢。我用simplexml尝试过,但它不起作用。 $输出似乎是一个布尔值(用gettype测试它)。有任何想法吗? – 2011-12-27 10:37:26

+0

请检查您的XML文档是否正确编码并且有效。 – 2011-12-27 10:42:30

+0

我想API – 2011-12-27 17:00:25