XPATH - 如何使用多个路径

时间:2012-03-13 21:09:18

标签: arrays xpath

我使用xpath来检索给定元素中某些链接(a)的文本值。然后我将结果推送到一个名为$ tableau的数组中。一切都很好:)事情是,我现在想要检索那些链接的href。所以我的数组中有文本值和href。另一件事是,我不知道该怎么做。希望有人能提供帮助。提前感谢您的回复。干杯。马克

$url = 'http://www.somesite.com';
$path = '.../a';
$tableau = array();

$dom = new DOMDocument();
@$dom->loadHTML($url);
$xpath = new DomXPath($dom);
$x = $xpath->query($path);

foreach ($x as $value)
     array_push($tableau, $value->nodeValue);

3 个答案:

答案 0 :(得分:1)

您可以使用关联数组

 the code might look like this(not sure abt the syntax though)
 arr = [ "1" => [ "text" => "value1" , "href" => "value1"],
         "2" => [ "text" => "value2", "href" => "value2"]];

检索所有锚标签的href的xpath xpression就是这样的

  ("//a/@href");

  //     --> select a from all the descendants of the root
  a      --> select the anchor tag
  @href  --> select the href of this anchor (@ to select attributes) 

将此表达式转换为等效的PHP代码

答案 1 :(得分:1)

试试这个:

foreach ($x as $value)
{
    array_push($tableau, $value->nodeValue, $value->getAttribute('href'));
}

答案 2 :(得分:0)

感谢javram和vireshad提供的提示,我设法找到解决方案。见下文:

$url = 'http://www.somesite.com';
$path = '.../a';
$tableau = array();

$dom = new DOMDocument();
@$dom->loadHTML($url);
$xpath = new DomXPath($dom);
$x = $xpath->query($path);

foreach ($x as $value)
     array_push($tableau, array($value->nodeValue, $value->getAttribute('href')));