2013-07-10 147 views
0

我正在將一些xml數據導入到一個php變量中,所以我可以在我的html網頁中輕鬆地調用它。我使用下面的代碼:php - xml數據解析

$ch  = curl_init(); 
$timeout = 5; 

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294"; 

$definition = simplexml_load_file($url); 

echo $definition->entry[0]->def; 

但是我的結果是:。

我不知道我在做什麼錯了,我也跟着PHP手冊,所以我猜測它的東西很明顯,但我只是沒有正確理解它。

從捲曲使用該鏈接實際的XML結果可見通過點擊下面的鏈接,我沒有貼它,因爲它是相當長的:

http://www.dictionaryapi.com/api/v1/references/sd3/xml/test?key=9d92e6bd-a94b-45c5-9128-bc0f0908103d

+1

它工作正常......你究竟在做什麼? (在你的'curl_close'和'print_r($ definition-> entry [0] - > def)'中添加一個分號而不是回顯它...這是一個SimpleXMLElement對象) – brbcoding

+1

- > def是一個SimpleXMLElement你是什麼期待什麼時候迴應?你真的想展示什麼價值? – tlenss

+0

http://php.net/simplexml.examples-basic - 如果你問一個關於XML/simplexml的問題,那你使用curl是沒有意義的。這可以用兩行代替(只是)。你也需要明確你的具體問題是什麼。你爲什麼期望工作?你期望它做什麼(應該給予什麼)?等等, – hakre

回答

1
<?php 
$ch = curl_init(); 
$timeout = 5; 

$url = "http://www.dictionaryapi.com/api/v1/references/collegiate/xml/define?key=0b03f103-f6a7-4bb1-9136-11ab4e7b5294"; 
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 
$data = curl_exec($ch); 
curl_close($ch); // you were missing a semicolon 


$definition = new SimpleXMLElement($data); 
echo '<pre>'; 
print_r($definition->entry[0]->def); 
echo '</pre>'; 

// this returns the SimpleXML Object 


// to get parts, you can do something like this... 
foreach($definition->entry[0]->def[0] as $entry) { 
    echo $entry[0] . "<br />"; 
} 

// which returns 

transitive verb 
14th century 
1 a 
:to determine or identify the essential qualities or meaning of 
b 
:to discover and set forth the meaning of (as a word) 
c 
:to create on a computer 
2 a 
:to fix or mark the limits of : 
b 
:to make distinct, clear, or detailed especially in outline 
3 
: 
intransitive verb 
:to make a 

Working Demo