2012-07-25 82 views
0

在我继续传奇的xpath和提取数据的过程中,我继续奋斗。我只需要包含在表格单元格中的两个值。我可以单独获得每个人,但在那里我无法访问其他人。我有细胞的,像这样xpath和提取多个值

<TR> 
<TD width="120" align="center" valign="top"> 
<A href="http://www..yadayada.com"> <!--the href I need to extract--> 
<IMG src="http://images.com/items/yada.gif" width="80" height="80" border="1"></A> 
<BR> 
<B>Random number PT</B><!--the text I need to extract--> 
</TD> 

我遍历像这样:

@$dom = new DOMDocument(); 
@$dom->loadHTML($rawPage); 
@$xpath = new DOMXPath($dom); 
@$queryResult = $xpath->query("..../tr/td[contains(b, 'PT') ]/b"); 

去的HREF链接和与之相似,

@$queryResult = $xpath->query("..../tr/td[contains(b, 'PT') ]/a"); 

得到我所需要的文本。然后我提取像这样

//for the text in b 
foreach ($queryResult as $result) 
{ 
echo $result->textContent . " text content<br>"; 
} 

和链接

//for the text in href 
foreach ($queryResult as $result) 
{ 
echo $result->getAttribute('href') . " href<br>"; 
} 

我不拉表中的每个TD,这就是为什么我匹配/td[contains(b, 'PT') ]那些有PT在。我已阅读有关工会和使用/td[contains(b, 'PT') ]/*[self::a or self::b,但我的每个错误与Invalid argument supplied for foreach()

我试过使用nextSibling和所有这一切,它只是空白,当我回声它。那么,我怎样才能从我的表格中获得这两个值呢?

+0

在'.../TR/TD [包含(b,'PT')]/b'什么是'PT'?你的html没有任何字词“PT”。 – 2012-07-25 16:36:18

+0

@VamanKulkarni,我在我的文章中纠正了这一点。 – KiloJKilo 2012-07-25 16:46:27

回答

1

您可以尝试

//td[contains(b, 'PT') ] 

而且

//td[contains(b, 'PT') ]/a 

两个查询应该工作,
使用现有的代码

queryResult = $xpath->query("//td[contains(b, 'PT') ]"); 
foreach ($queryResult as $result) 
{ 
    echo $result->textContent . " text content<br>"; 
} 

$queryResult = $xpath->query("//td[contains(b, 'PT') ]/a"); 
foreach ($queryResult as $result) 
{ 
    echo $result->getAttribute('href') . " href<br>"; 
} 
+0

我已经这样做了,作为单个xpath查询的一部分,但是,我不知道如何实现这一点。我写两个单独的xpath查询? – KiloJKilo 2012-07-25 17:33:22

+0

你描述它的方式,它会发布b和一个单独的。我只是将href循环移到第一个循环中,以便将匹配的href与相应的b一起发布。谢谢 – KiloJKilo 2012-07-25 18:03:45