了解如何从结果中删除无用的垃圾:
] => Array ( [] =>
我的PHP代码:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
print_r($result);
?>
示例输出:
Array ( [] => Array ( [] => slant distance ) [Atlantic Southeast Airlines flight 5520
{
{1}} {
{1}} {
{1}} {
{1}}
每次休息时都会有一个] => Array ( [] => 23 miles SW ) [Volaris flight 940
标签,但不是很重要。
答案 0 :(得分:1)
Try this:
<?php
$url = 'http://api.wolframalpha.com/v2/query?input=planes+seen+from+dallas&appid=2UJ62E-Q6RT3T89P8';
$parser = new XMLReader;
$parser->open($url);
while ($parser->read()) {
if ($parser->nodeType === XMLReader::ELEMENT) {
while ($parser->name === 'pod' && $parser->getAttribute('title') !== 'Result')
$parser->next('pod'); // jump to the next pod node
if ($parser->name === 'plaintext') {
$str = $parser->readString();
$parser->close();
break;
}
}
}
$lines = explode("\n", $str);
$result = array();
foreach ($lines as $line) {
$fields = explode(' | ', $line);
$flight = array_shift($fields);
$flight = $flight . "<hr>"; //DELETE IF DOESN'T WORK
if ($flight === '')
$cols = $fields;
elseif (isset($fields[1])) {
$result[$flight][$cols[0]] = $fields[0];
$result[$flight][$cols[1]] = $fields[1];
}
}
foreach($result as $key=>$value)
{
echo $key;
foreach($value as $value1){
echo $value1;
echo " ";
}
}