【问题标题】:php - xml data parsingphp - xml数据解析
【发布时间】:2013-07-08 20:21:10
【问题描述】:

我正在努力将一些 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

【问题讨论】:

  • 一切正常...您到底想做什么? (在您的 curl_closeprint_r($definition->entry[0]->def) 上添加一个分号,而不是回显它......这是一个 SimpleXMLElement 对象)
  • ->def 是一个 SimpleXMLElement,当你回显这个时,你期望什么?你真正想展示什么价值?
  • php.net/simplexml.examples-basic - 如果你问一个关于 XML/simplexml 的问题,你使用 curl 是没有意义的。这可以写成两行(刚刚做了)。您还需要明确您的具体问题是什么。你为什么期望它起作用?你期望它做什么(应该给出什么)?等等,

标签: php xml xml-parsing nsxmlelement


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    相关资源
    最近更新 更多