【问题标题】:Rewriting to avoid the use of Zend重写以避免使用 Zend
【发布时间】:2014-11-10 05:15:08
【问题描述】:

我正在尝试遵循在以下位置找到的教程:https://www.ibm.com/developerworks/xml/library/x-phpwikipedia/index.html

所有教程都使用 Zend 框架。我想知道如果可能的话,如何调整这段代码以避免使用 Zend(或任何其他先决条件)?请看下面的例子。谢谢。

<?php
// load Zend classes
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Rest_Client');

// define category prefix
$prefix = 'hollywood';

try {
// initialize REST client
$wikipedia = new Zend_Rest_Client('http://en.wikipedia.org/w/api.php');

// set query parameters
$wikipedia->action('query');
$wikipedia->list('allcategories');
$wikipedia->acprefix($prefix);
$wikipedia->format('xml');

// perform request
// iterate over XML result set
$result = $wikipedia->get();
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
?>
<html>
<head></head>
<body>
<h2>Search results for categories starting with 
  '<?php echo $prefix; ?>'</h2>
<ol>
<?php foreach ($result->query->allcategories->c as $c): ?>
  <li><a href="http://www.wikipedia.org/wiki/Category:
    <?php echo $c; ?>"><?php echo $c; ?></a></li>
<?php endforeach; ?>
</ol>
</body>
</html>

【问题讨论】:

    标签: php zend-framework


    【解决方案1】:

    这样的事情应该可以工作:

    <?php
    $prefix = 'allcategories';
    $url = "http://en.wikipedia.org/w/api.php?action=query&list={$prefix}&format=json&continue=";
    $res = file_get_contents($url);
    $data = json_decode($res);
    ?>
    <html>
    <head></head>
    <body>
    <h2>Search results for categories starting with 
      '<?php echo $prefix; ?>'</h2>
    <ol>
    <?php foreach ($data->query->allcategories as $c): 
    ?>
      <li><a href="http://www.wikipedia.org/wiki/Category:<?php echo $c->{'*'}; ?>"><?php echo $c->{'*'}; ?></a></li>
    <?php endforeach; ?>
    </ol>
    </body>
    </html>
    

    在这种情况下,请求将使用 json 格式,它更易于使用:)

    【讨论】:

    • 嗨,感谢@FDIM 的帮助,但很抱歉,由于没有创建对象,因此无法以上面显示的格式工作。
    • 我已经更新了@Oroku 的答案,这次已经测试过了。
    【解决方案2】:

    正如 IBM 文章所述,Wiki API 默认以 XML 返回结果,但也可以在 JSONWDDXYAMLPHP serialized 中返回结果。

    基本上,您只需要创建一个HTTP request 来请求正确的信息并解析返回的结果。例如单击此链接http://en.wikipedia.org/w/api.php?action=query&list=allcategories&acprop=size%20&acprefix=hollywood&format=xml,您会看到它在浏览器中返回XML 结果,您几乎可以使用任何语言进行循环和解析。

    要在PHP 中请求xml 数据的内容,您可以使用file_get_contents($target_url);,然后您就不必依赖创建zend rest 客户端。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-10
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-10
      相关资源
      最近更新 更多