PHP Xpath 不返回所有值


PHP Xpath not returning all value

请帮助Xpath...

以下脚本将使用 Xpath 抓取 URL 的主体

<?php
//sentimen order
if (PHP_SAPI != 'cli') {
echo "<pre>";
}
require_once __DIR__ . '/../autoload.php';
$sentiment = new 'PHPInsight'Sentiment();
require_once 'Xpath.php';

$startUrl = "http://news.sky.com/story/1445575/suspect-held-over-shooting-of-ferguson-police/";
$xpath = new XPATH($startUrl);
// We starts from the root element
$query = '/html/body/div[2]/div[3]/article/div/div[2]/div[2]/p[3]';

$strQuery = $xpath->query($query);
$strNode = $strQuery->item(0)->nodeValue;
$result = array($strNode);
foreach ($result as $string) {
// calculations:
$scores = $sentiment->score($string);
$class = $sentiment->categorise($string);
// output:
echo "Strings $string 'n";
echo "Dominant: $class, scores: ";
print_r($scores);
echo "'n";
}

上面的脚本运行良好,除了数组循环...Xpath不会抓取所有内容,而只会抓取主体的第一行。

我认为问题出在数组循环和 foreach 上...

任何人请帮助修复此循环....

你只获取一个段落。此外,您只将一个字符串放入数组中。

您可能正在寻找更多类似的东西:

foreach ($xpath->query('
//header/h1
|//header/p
|//header//p[@class="last-updated__text"]
|//div[@class="story__content"]/p') as $p) {
    echo string_normalize($p->textContent), "'n'n";
}
function string_normalize($string)
{
    return preg_replace('~'s+~u', ' ', trim($string));
}

输出:

弗格森警方枪击案:嫌疑人被指控

一名检察官说,这名20岁的嫌疑人声称他在与其他人发生争执时开枪,并没有瞄准警察。

05:19, 英国, 星期一 16 三月 2015

天空新闻美国团队

一名嫌疑人被指控与上周在密苏里州弗格森枪击和伤害两名警察有关。

圣路易斯县检察官罗伯特麦卡洛克在新闻发布会上说,被告是20岁的杰弗里威廉姆斯。

他说,嫌疑人是当地居民,面临两项一级袭击罪。

周六晚上被捕的威廉姆斯还被指控从车辆上开枪。

"他已经承认他参与了开枪,"麦卡洛克告诉记者。