2011-09-29 38 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