【问题标题】:getting value using xpath and dom in php在 php 中使用 xpath 和 dom 获取价值
【发布时间】:2012-12-06 17:27:19
【问题描述】:

这是我要解析的html部分:

<center>
<table border="0" cellpadding="0" cellspacing="0"  >
<td>
Some text
<br>
<font color=brown>label0</font>Value0
<br>
<font color=brown>Label1</font>Value1.<br>
Some text
<br>

<font color=brown>Label2</font>Value2<br>
</td>
</table>

</center>

我想要获取 Value0 和 Value1。

如果我用这个:

$index=$element->nodeValue;

其中元素是对.../font 的查询我得到Label0,1,2。但我想要价值。怎么做?如果有需要我也可以提供更多代码。

【问题讨论】:

标签: php html dom xpath


【解决方案1】:

不妨试试:

$index=$element->nextSibling->nodeValue;

获取字体节点后节点的值。

【讨论】:

    【解决方案2】:
    <center>
    <table border="0" cellpadding="0" cellspacing="0"  >
    <td>
    Some text
    <br>
    <font color=brown>label0</font><span>Value0</span>
    <br>
    <font color=brown>Label1</font><span>Value1.</span><br>
    Some text
    <br>
    
    <font color=brown>Label2</font>Value2<br>
    </td>
    </table>
    </center>
    

    尝试像上面一样放置跨度,而不是查询跨度的字体查询... 希望它会有所帮助..

    【讨论】:

      【解决方案3】:

      试试这个:

      $str = '<center>
      <table border="0" cellpadding="0" cellspacing="0"  >
      <td>
      Some text
      <br>
      <font color=brown>label0</font>Value0
      <br>
      <font color=brown>Label1</font>Value1.<br>
      Some text
      <br>
      
      <font color=brown>Label2</font>Value2<br>
      </td>
      </table>
      </center>';
      
      $dom = new DOMDocument();
      $dom->loadHTML($str);
      $dom->preserveWhiteSpace = false;
      $dom->validateOnParse = true;
      
      $xpath = new DOMXPath($dom);
      $nodes = $xpath->query("//font");
      foreach ($nodes as $node) {
          echo trim( $node->nextSibling->nodeValue ) . "\n";
      }
      

      希望这会有所帮助。

      【讨论】:

      • 您的查询仅匹配根中的font。删除// 以获取整个文档中的所有font
      • @Jelmer 你有没有尝试运行代码。它完全符合 OP 的要求,并且符合发布的 html 结构。我完全了解// 的作用。尝试先解决你的答案,这意味着 CSS 的使用和什么不是。
      • php.net/manual/en/domxpath.query.php 它声明'//'用于从根元素开始。在这种情况下,&lt;center&gt; 是,但是如果你再看一下这个问题。他说this the part of the html i want to parse 换句话说,&lt;center&gt; 不是根。
      【解决方案4】:
      $dom = new DOMDocument();
      $xpath = new DOMXPath($dom);    
      $xpath->loadHTML('link/to/html');
      $fonts = $xpath->query('font');
      foreach ($fonts as $font){
          echo $font->nextSibling->nodeValue;
      }
      

      上面的脚本将回显&lt;font&gt; 中的所有值。

      但是拜托,你为什么不使用CSS

      【讨论】:

      • 我还没有创建那个网站。我刚刚被告知要从中解析一些值,所以我必须处理当前格式。
      • @ghostrider 好吧。谢谢回复:)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2016-04-05
      • 1970-01-01
      • 2011-12-21
      • 2015-04-02
      • 1970-01-01
      相关资源
      最近更新 更多