2011-09-29 53 views
0

我正在使用PHP发送XML到Web服务器,并且服务器返回XML响应。我需要帮助解析响应中的值!我已阅读过SimpleXML指令,但我的理解是,所有这些仅适用于XML数据已经创建但需要解析的情况。这是迄今为止我的PHP脚本:He!p with SimpleXML for PHP response in PHP

<?php 
$ch = curl_init("http://api.online-convert.com/queue-insert"); 
$count = $_POST['count']; 
$file = "testdoc2.txt"; 
$fh = fopen($file, 'w'); 
$carriageReturn = "\n"; 
fwrite($fh, $count); 
fclose($fh); 

$request["queue"] = file_get_contents($count); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, $request); 
$response = curl_exec($ch); 
curl_close ($ch); 
echo $response; 

$xmlstr = simplexml_load_string($response); 

$file = "testdoc.txt"; 
$fh = fopen($file, 'w'); 
$carriageReturn = "\n"; 
fwrite($fh, $xmlstr); 
fclose($fh); 


?> 

需要被解析的XML响应是这样的:

<?xml version="1.0" encoding="utf-8"?> 
<queue-answer> 
    <status> 
    <code>0</code> 
    <message>Successfully inserted job into queue.</message> 
    </status> 
    <params> 
    <downloadUrl>http://www.online-convert.com/result/35f6ddbcc2ca58e7e98addc7c2efd6eb</downloadUrl> 
    <hash>35f6ddbcc2ca58e7e98addc7c2efd6eb</hash> 
    </params> 
</queue-answer> 

我只需要提取值,并将其展示给用户。我是一名iPhone开发人员。

+0

我想,这可能是有用的http://debuggable.com/posts/parsing-xml-using-simplexml:480f4dfe-6a58-4a17-a133-455acbdd56cb –

回答

0

您首先必须创建request xml document并将其发送到服务器,例如, (没有错误处理等,没有由于缺少API密钥的测试):

$request = new SimpleXMLElement('<queue><apiKey/><targetType/><targetMethod/><testMode/><sourceUrl/></queue>'); 
$request->apiKey = 'abcdefghijklmnopqrstuvwx'; 
$request->targetType = 'image'; 
$request->targetMethod = 'convert-to-jpg'; 
$request->testMode = 'false'; 
$request->sourceUrl = 'http://whatever'; 
$ch = curl_init("http://api.online-convert.com/queue-insert"); 
curl_setopt($ch, CURLOPT_HEADER, 0); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POSTFIELDS, array('queue'=>$request->asXml())); 
$response = curl_exec($ch); 
// TODO: might want to test the response code here, see curl_get_info/CURLINFO_HTTP_CODE 
curl_close ($ch); 

,那么你需要解析响应

$queueAnswer = simplexml_load_string($response); 
echo 'status code:', $queueAnswer->status->code; 
// in case of success you should be able to access the values via 
echo ' url:', queueAnswer->params->downloadUrl; 
echo ' hash:', queueAnswer->params->hash; 
0

您可以使用此

$xml=simplexml_load_string($response); 
foreach($xml->children() AS $child) 
{ 
    echo $child->getName().”:”.$child.”<br/>”; 
} 

解析XML文件,你可以把一个if条件,只提取所需的信息。

+0

我只需要得到的值,所以它会是: '$ xml = simplexml_load_string($ response); for($ xml-> params AS $ child) { echo $ child-> hash。“:”。$ child。“
”; } '' – Prajoth

+0

的foreach($ XML->儿童()作为$子) { \t如果($儿童安全>的getName()== 'PARAMS'){ \t \t的foreach($儿童安全>儿童( )AS $ paramChild){ \t \t \t如果($ paramChild->的getName()== '散列'){ \t \t \t \t回声 “的散列值是” $ paramChild。 \t \t \t} \t \t} \t} }' – Srinath

+0

上面的代码会得到你从服务器得到的回应的哈希值。 – Srinath