【问题标题】:xml parser with curl带有 curl 的 xml 解析器
【发布时间】:2011-11-05 20:11:18
【问题描述】:

我制作了一个 curl 脚本,使用 curl 解析 xml url,如下所示

<?php 

$url = 'http://www.slideshare.net/api/2/search_slideshows?api_key=OKlHvfPo&ts=1320522764&hash=12bf522db6f39d8f96ec3d9187a88e32b02205a8&q=electrical+engineering&page=4&download=0&items_per_page=25';

echo $url;

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Your application name');

$query = curl_exec($ch);
curl_close($ch);

$array = (array) simplexml_load_string($query);

//echo '<pre>';
//print_r($array);

foreach ($array as $key) {
    echo $key['Title']. "<br>";
}
?>

数组 $array 打印得非常完美,但我不明白如何迭代这个数组。因为我使用的 foreach 循环不起作用。它只给出两个空结果。请帮忙

【问题讨论】:

  • 请发布print_r($array)的输出。我怀疑你需要的是foreach ($array as $key=&gt;$value)
  • Array (Meta Stack Overflow => SimpleXMLElement Object ([Query] => 电气工程 [ResultOffset] => SimpleXMLElement Object () [NumResults] => 25 [TotalResults] => 36839) [幻灯片] => Array ([0] => SimpleXMLElement Object ([ID] => id value [Title] => title value [Description] => descript [Status] => 2)
  • 请不要在这里,使用格式正确的代码标签中的此数组编辑您的问题。

标签: php xml curl


【解决方案1】:

Simplexml 需要对文件缓冲区的引用。阅读 curl_setopt,特别是 CURLOPT_FILE。 curl_exec 返回(真/假)。你肯定不希望这样。

这是一个 perl 示例,说明如何通过 curl 使用缓冲区:

#!/usr/bin/perl -w
use strict;
use WWW::Curl::Easy;

my $curl = new WWW::Curl::Easy;
$curl->setopt(CURLOPT_HEADER, 0);
$curl->setopt(CURLOPT_URL, $url);
$curl->setopt(CURLOPT_FAILONERROR, 1);
$::errbuf="";
$curl->setopt(CURLOPT_ERRORBUFFER, "::errbuf");

my $response_body;
open (my $fileb, ">", \$response_body);
$curl->setopt(CURLOPT_WRITEDATA,$fileb);
my $retcode;
(($retcode = $curl->perform) == 0) and do {
    # do something with $response_body
}

Perl 和 PHP 类似,你应该明白了。

【讨论】:

【解决方案2】:

这应该可行:

foreach ($array['ResultOffset'] as $key => $val) {
    echo $key . ' -> ' . $val;
}

编辑:

您必须删除 simplexml_load_string 的(数组)类型转换。它应该已经是一个可迭代的对象了。

$xml = simplexml_load_string($query);
foreach ($xml as $element) {
    if ($element->children()) {
        foreach ($element->children() as $el) {
            echo $el;
        }
    } else {
        echo $element;
    }
}

【讨论】:

  • 这不起作用。这给出了一个错误“为 foreach 提供的参数无效”
猜你喜欢
  • 2011-09-05
  • 2013-12-11
  • 1970-01-01
  • 2012-10-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 2015-10-30
相关资源
最近更新 更多