【问题标题】:Advice to modify code to show multiple xpaths (PHP)建议修改代码以显示多个 xpath (PHP)
【发布时间】:2017-06-09 06:38:03
【问题描述】:

我在一个网站上使用这个测试代码来学习如何做。我试图基本上从网络上抓取特定 div 类中包含的所有内容,并将其回显到另一个站点上。下面的这个成功地完成了这个,只在网站上显示了第一个 div 类,而我希望它显示所有。下面的代码吐出这个结果: string(107) " DJIA 21182.53 +8.84(0.04%) "

<?php 

 $doc = new DOMDocument;

// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

// Most HTML Developers are chimps and produce invalid markup...
$doc->strictErrorChecking = false;
$doc->recover = true;

$doc->loadHTMLFile('http://www.nbcnews.com/business');

$xpath = new DOMXPath($doc);

$query = "//div[@class='market']";

$entries = $xpath->query($query);
var_dump($entries->item(0)->textContent);

?>

然而,源代码也有这些条目:

    <div class="market">
            <span class="market_item market_name">DJIA</span>
            <span class="market_item market_price">21182.53</span>
            <span class="market_item market_price  is-positive ">
            +8.84(0.04%)</span>
          </div>
          <div class="market">
            <span class="market_item market_name">NASDAQ</span>
            <span class="market_item market_price">6321.76</span>
            <span class="market_item market_price  is-positive ">
            +24.38(0.39%)</span>
          </div>
          <div class="market">
            <span class="market_item market_name">S&amp;P 500</span>
            <span class="market_item market_price">2433.79</span>
            <span class="market_item market_price  is-positive ">
            +0.65(0.03%)</span>
          </div>

关于我需要修改什么以显示所有这 3 个的想法?猜测它可能与项目(O)有关,但是当我修改它时,我破坏了代码。 我非常想改变的第二件事是停止在实际回显文本之前显示“字符串(___)”。

真的很感激!!谢谢。

【问题讨论】:

    标签: php html class xpath


    【解决方案1】:

    $entries 是可以迭代的对象:

    $entries = $xpath->query($query);
    foreach ($entries as $entry) {
        echo trim($entry->textContent);  // use `trim` to eliminate spaces
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-01-31
      • 2022-08-09
      • 2022-12-18
      • 2022-11-16
      • 2015-01-01
      • 1970-01-01
      • 2019-06-29
      • 1970-01-01
      相关资源
      最近更新 更多