【发布时间】:2017-06-19 00:37:16
【问题描述】:
使用数据抓取进行测试。我正在抓取的输出是百分比。所以我基本上打了一个
echo "%<br>";
最后输出的实际数字是
echo $ret_[66];
但是存在一个问题,即百分比实际上也出现在数字之前,这是不可取的。这是输出:
%
-0.02%
而我想要得到的只是 -0.02%
很明显,我在 PHP 上做错了什么。我真的很感激任何反馈/解决方案。谢谢!
完整代码:
<?php
error_reporting(E_ALL^E_NOTICE^E_WARNING);
include_once "global.php";
$doc = new DOMDocument;
// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;
$doc->strictErrorChecking = false;
$doc->recover = true;
$doc->loadHTMLFile('http://www.moneycontrol.com/markets/global-indices/');
$xpath = new DOMXPath($doc);
$query = "//div[@class='MT10']";
$entries = $xpath->query($query);
foreach ($entries as $entry) {
$result = trim($entry->textContent);
$ret_ = explode(' ', $result);
//make sure every element in the array don't start or end with blank
foreach ($ret_ as $key => $val){
$ret_[$key] = trim($val);
}
//delete the empty element and the element is blank "\n" "\r" "\t"
//I modify this line
$ret_ = array_values(array_filter($ret_,deleteBlankInArray));
//echo the last element
echo $ret_[66];
echo "%<br>";
}
【问题讨论】:
-
“出现在数字之前”和一个循环 (
foreach) 表示其中一行可能没有回应echo $ret_[66];。 -
我猜这和这个有关?
deleteBlankInArray或许可以试试:if ($ret_[66]) { echo $ret_[66]; echo "%<br>"; } -
谢谢贾里德,我认为你是对的。我实际上找到了一个更简单的解决方案,即在底部创建另一个 php 文件 "; ?> 我会调查你的解决方案,因为它可能更有效。谢谢。
-
是的,检查
if (isset($ret_[66])) { echo $ret_[66]."%<br>"; }
标签: php xpath output percentage