【问题标题】:Extract text and image src with PHP DomDocument使用 PHP DomDocument 提取文本和图像 src
【发布时间】:2014-10-16 12:10:58
【问题描述】:

我正在尝试提取 img src 和 div id="Ajax" 内的 TD 文本,但我无法用我的代码提取 img。它只是忽略了 img src。如何也提取 img src 并将其添加到数组中?

HTML:

<div id="Ajax">
<table cellpadding="1" cellspacing="0">
<tbody>
<tr id="comment_1">
<td>20:28</td>
<td class="color">
</td>
<td class="last_comment">
Text<br/>
</td>
</tr>
<tr id="comment_2">
<td>20:25</td>
<td class="color">
</td>
<td class="comment">
Text 2<br/>
</td>
</tr>
<tr id="comment_3">
<td>20:24</td>
<td class="color">
<img src="http://url.ext/img/image02.jpeg" alt="img alt 2"/>
</td>
<td class="comment">
Text 3<br/>
</td>
</tr>
<tr id="comment_4">
<td>20:23</td>
<td class="color">
<img src="http://url.ext/img/image01.jpeg" alt="img alt"/>
</td>
<td class="comment">
Text 4<br/>
</td>
</tr>
</div>

PHP:

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);
$contentArray = array();
$doc = $doc->getElementById('Ajax');
$text = $doc->getElementsByTagName ('td');
foreach ($text as $t)
{
$contentArray[] = $t->nodeValue;
}
print_r ($contentArray);

谢谢。

【问题讨论】:

  • 你对任何图像标签都不做任何事情?

标签: php text extract domdocument


【解决方案1】:

您正在使用$t-&gt;nodeValue 获取节点的内容。 &lt;img&gt; 标记为空,因此没有可返回的内容。获取 src 属性的最简单方法是 XPath。

例子:

$html = file_get_contents($url);

$doc = new DOMDocument();
@$doc->loadHTML($html);
$xpath = new DOMXpath($doc);
$expression = "//div[@id='Ajax']//tr"; 
$nodes = $xpath->query($expression); // Get all rows (tr) in the div

$imgSrcExpression = ".//img/@src";
$firstTdExpression = "./td[1]";
foreach($nodes as $node){ // loop over each row
  // select the first td node
  $tdNodes = $xpath->query($firstTdExpression ,$node);
  $tdVal = null;
  if($tdNodes->length > 0){
    $tdVal = $tdNodes->item(0)->nodeValue;
  }

  // select the src attribute of the img node
  $imgNodes = $xpath->query($imgSrcExpression,$node);
  $imgVal = null;
  if($imgNodes ->length > 0){
    $imgVal = $imgNodes->item(0)->nodeValue;
  }
}

(注意:代码可能包含拼写错误)

【讨论】:

  • 谢谢,我通过将 $xpath 替换为 $xpath->query 来实现它。对吗?
  • 是的。更新了示例。如果它解决了您的问题,请接受答案。
猜你喜欢
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2013-02-25
  • 2011-06-19
相关资源
最近更新 更多