XPath - 在一些文本后选择锚点

时间:2014-07-29 14:47:32

标签: php xpath domxpath

我想从此示例代码中获取数据:

<div id="text">

(sd) <a href="http://example.com/somefiledfs.flv">http://example.com/somefiledfs.flv</a>
 - 380 kbps 
 - <a href='/player.swf?config={"clip":{"url":"http://example.com/somefiledfs.flv"}'>Watch</a><br>

(576p) <a href="http://example.com/hgyj.mp4">http://example.com/hgyj.mp4</a>
 - 780 kbps 
 - <a href='/player.swf?config={"clip":{"url":"http://example.com/hgyj.mp4"}'>Watch</a><br>

</div>

我想把它当成:

sd - http://example.com/somefiledfs.flv

576p - http://example.com/hgyj.mp4

等等。

能帮忙吗?我试图使用&#34; // div [@id =&#39; text&#39;] / a&#34;和祖先/先前,但我无法解决。

1 个答案:

答案 0 :(得分:1)

这是一个有效的PHP片段,基本上循环遍历所有链接然后检查上一个节点是否与sd|576p匹配(如果需要,可以在此处扩展更多格式...)

<?php 
$html = <<<HTML
<div id="text">
  (sd) <a href="http://example.com/somefiledfs.flv">http://example.com/somefiledfs.flv</a>   
    - 380 kbps 
    - <a href='/player.swf?config={"clip":{"url":"http://example.com/somefiledfs.flv"}'>Watch</a><br>

  (576p) <a href="http://example.com/hgyj.mp4">http://example.com/hgyj.mp4</a>
    - 780 kbps 
    - <a href='/player.swf?config={"clip":{"url":"http://example.com/hgyj.mp4"}'>Watch</a><br>

</div>
HTML;

$dom = new DOMDocument();
$dom->loadHTML($html);
$xpath = new DOMXPath($dom);

$as = $xpath->query("//div[@id='text']/a");

foreach ($as as $a) {
  $prev = $a->previousSibling->nodeValue;

  if (preg_match("/sd|576p/", $prev, $matches)) {
    echo $matches[0]." - ".$a->nodeValue."\r\n";
  }
}
?>

这是指向代码段的链接:https://eval.in/173038

相关问题