Xpath代码在firepath中工作,但在php脚本中不起作用

时间:2012-11-08 04:29:08

标签: php xpath firepath

        $html = new DOMDocument();
        @$html->loadHtmlFile($url);
        $xpath = new DOMXPath( $html );
        //Query to pull all reviews on the page
        $q="//div[starts-with(@id,empReview_)]/h3/meta[1]/@content";
        $nodelist = $xpath->query($q);

        foreach ($nodelist as $n){
            echo $n->nodeValue;
            echo"<br><br>";

        }

我正在尝试在以下XML上运行查询:

<div id="empReview_2055942" class="employerReview" itemscope="" itemtype="http://schema.org/Review">
    <h2 class="summary">
    <h3 class="review-microdata-heading">
        <span class="gdRatingStars"> </span>
        Former 
        <span itemprop="author">IT Engineer Intern in Santa Clarita, CA</span>
        <meta content="4" itemprop="reviewRating"/>

使用Firepath时该元素是正确的,但是没有通过php中的查询回显该值。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

您的xpath查询错误,应该是:

$q="//div[starts-with(@id,empReview_)]/h2/h3/meta[1]/@content";

(你缺少'h2')。你的代码应该是这样的......

$html = new DOMDocument();

$html->loadHtml('
  <div id="empReview_2055942" class="employerReview" itemscope="" itemtype="http://schema.org/Review">
      <h2 class="summary">
      <h3 class="review-microdata-heading">
          <span class="gdRatingStars"> </span>
          Former 
          <span itemprop="author">IT Engineer Intern in Santa Clarita, CA</span>
          <meta content="4" itemprop="reviewRating"/>
      </h3> <!-- presumably your input has closing tags -->
      </h2>
  </div>
  <div id="empReview_2055947" class="employerReview" itemscope="" itemtype="http://schema.org/Review">
      <h2 class="summary">
      <h3 class="review-microdata-heading">
          <span class="gdRatingStars"> </span>
          Former 
          <span itemprop="author">Some Other Random Thing</span>
          <meta content="7" itemprop="reviewRating"/>
      </h3>
      </h2>
  </div>
');

$xpath = new DOMXPath( $html );
//Query to pull all reviews on the page
$q="//div[starts-with(@id,empReview_)]/h2/h3/meta[1]/@content";
$nodelist = $xpath->query($q);

foreach ($nodelist as $n){
  echo $n->nodeValue;
  echo"<br><br>\n";
}

我得到以下输出:

4<br><br>
7<br><br>