【问题标题】:Help echoing array from php function帮助从 php 函数回显数组
【发布时间】:2011-05-15 03:20:00
【问题描述】:

好吧,我仍在学习我的 php 函数,但这段特殊的代码让我陷入了困境。维基百科查询部分的信用转到http://www.barattalo.it/2010/08/29/php-bot-to-get-wikipedia-definitions/。我认为这看起来很有趣,并试图使用提供的代码来回显函数中的数据。这就是我所拥有的:

<?php
    function wikidefinition($s) {
        $url = "http://wikipedia.org/w/api.php?action=opensearch&search=".urlencode($s)."&format=xml&limit=1";
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPGET, TRUE);
        curl_setopt($ch, CURLOPT_POST, FALSE);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_NOBODY, FALSE);
        curl_setopt($ch, CURLOPT_VERBOSE, FALSE);
        curl_setopt($ch, CURLOPT_REFERER, "");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 6.1; he; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8");
        $page = curl_exec($ch);
        $xml = simplexml_load_string($page);
        if((string)$xml->Section->Item->Description) {
            return array((string)$xml->Section->Item->Text, (string)$xml->Section->Item->Description, (string)$xml->Section->Item->Url);
        } else {
            return "blank";
        }
    }

    $define = wikidefinition("test");
    echo $define;

?>

然而,这只是回显“数组” 我知道代码正在进入 if/else 语句,因为如果您更改 "$define = wikidefinition("test");" 中的输入对于一些随机键组合,例如“qoigenqnge”,它会回显“空白”我无法弄清楚为什么它只回显“数组”而不是数组内的数据。可能是一些愚蠢的事情,但我已经阅读了一段时间的数组并且找不到任何信息。任何帮助都会非常感谢!

【问题讨论】:

  • 请格式化您的代码,只需一分钟,让您的问题更容易回答。
  • 我的错,我忘了这样做。感谢您的提醒

标签: php arrays function echo


【解决方案1】:

你试过了吗:

print_r($define);

而不是echo ?

【讨论】:

  • 这正是我要说的:)
  • 啊,好电话,我之前尝试过 print_r 但设置错误。那行得通,但我知道 print_r 更像是一个调试命令,有什么方法可以得到比这更好的结果吗?例如。只是测试的定义?
  • @jangoforhire 听起来您想要回显的是数组的元素之一 - 在您转出数组之后,查看键,然后尝试回显它。类似 echo $define['definition'];
  • 实际上,如果这就是您要查找的全部内容,您可能应该只在函数中返回定义。如果不需要,则无需分配数组:)
  • 知道了,我现在只是在看那个。非常感谢您的帮助!已标记答案。
猜你喜欢
  • 2010-11-20
  • 2010-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多