0

我正在努力将一些 xml 数据放入 php 变量中,以便可以在我的 html 网页中轻松调用它。我在下面使用此代码:

$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 手册,所以我猜这很明显,但我只是没有正确理解它。

通过单击下面的链接可以看到 cURL 中使用的链接的实际 xml 结果,我没有发布它,因为它相当长:

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

4

1 回答 1

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 

工作演示

于 2013-07-10T18:54:11.930 回答