2009-07-23 71 views
1

我想了解這將如何工作我如何解析xml數據在php

爲了測試的目的,我做了兩個網站。

一個呼籲從另一個

我與拉的file_get_contents

如果我贊同它,我可以看到一個串關數據的XML數據的REST服務。

但是我怎樣才能使用它的simpelxml,從節點本身提取數據?

如果我使用simplexml_load_file($ url),我得到一些錯誤,說xml聲明只允許 在文檔的開始?

我有這個在我testfile的

<?php 

$url='http://www.woonbel.nl/gps/setgpsloc'; 
//not working 
$xml =simplexml_load_file($url); 

print_r($xml); 

//just a string 
$xml=file_get_contents($url); 
echo "<h3>$xml</h3><br>"; 

?> 

,這是我送的XML。

我從一個類文件發送這個文件,我把它包含在我的php文件 的頂部,如果我確定webservice被調用,也許這與處理聲明錯誤有關?

header('Content-type: text/xml'); 
echo "<?xml version=\"1.0\"?>\n"; 
echo "<response>\n"; 
echo "\t<status>$status_code</status>\n"; 
echo "\t<fout>Geen</fout>\n"; 
echo "</response>"; 

謝謝,理查德

+2

沒有看到特定文件,很難說出錯是什麼。 – 2009-07-23 18:50:59

+0

xml看起來不錯。檢查file_get_contents返回的內容,並在<?xml – koen 2009-07-23 22:38:58

+0

開始之前檢查任何內容file_get_contents返回字符串中xml標記中包含的數據。我可以看到,因爲我已將它回顯到頁面。 – Richard 2009-07-24 02:47:28

回答

0

你取到聲明之前的空行?

+0

我需要什麼聲明? – Richard 2009-07-23 19:14:46

3

聽起來好像文件頂部有一個空行,它應該以xml聲明開頭。例如:

<?xml version="1.0" encoding="utf-8"?> 
0

你的REST服務應該返回XML內容是這樣的:

<?xml version="1.0" encoding="utf-8"?> 
<results> 
    <result> 
    <value awesome="true">LOLCATS</value> 
    </result> 
</results> 

你會然後做這些方針的東西消耗在其他網站,REST服務:

$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml')); 

foreach($xml->result as $result) { 
    $value = $result->value; 
    $awesome = $result->attributes()->awesome; 
    // do something here with our values and attributes 
} 

SimpleXML的PHP​​文檔包含更復雜/更真實的示例。

針對您的特殊XML:

$xml = simplexml_load_string(file_get_contents('http://example.com/rest.xml')); 

$status = $xml->status; 
$fout = $xml->fout; 
0

錯誤信息中明確指出,有一個空白,行數和文字,在XML數據的開始。這可能是文件編碼 - 組織。