从PHP中提取HTML的某些部分


Extracting certain portions of HTML from within PHP

好的,所以我正在用PHP编写一个应用程序来检查我的网站是否所有链接都有效,这样我就可以在必要时更新它们。

我遇到了一个问题。我曾尝试使用SimpleXml和DOMDocument对象来提取标记,但当我使用示例站点运行应用程序时,如果我使用SimpleXml对象类型,通常会出现大量错误。

那么,有没有一种方法可以像使用SimpleXml一样简单地扫描html文档中的href属性呢?

    <?php
    // what I want to do is get a similar effect to the code described below:
    foreach($html->html->body->a as $link)
    {
         // store the $link into a file
         foreach($link->attributes() as $attribute=>$value);
         {
              //procedure to place the href value into a file
         }
    }
?>

所以基本上,我正在寻找一种方法来完成上述操作。问题是,我现在很困惑,我应该如何处理带有html代码的字符串…

为了清楚起见,我使用以下原始方式获取html文件:

<?php
$target      = "http://www.targeturl.com";
$file_handle = fopen($target, "r");
$a = "";
while (!feof($file_handle)) $a .= fgets($file_handle, 4096);
fclose($file_handle);
?>

任何信息都将是有用的,以及任何其他语言的替代方案,其中上述问题得到了更优雅的解决(python、c或c++)

您可以使用DOMDocument::loadHTML

下面是我们编写的HTML解析工具使用的一组代码。

$target = "http://www.targeturl.com";
$result = file_get_contents($target);
$dom = new DOMDocument;
$dom->preserveWhiteSpace = false;
@$dom->loadHTML($result);
$links = extractLink(getTags( $dom, 'a', ));
function extractLink( $html, $argument = 1 ) {
  $href_regex_pattern = '/<a[^>]*?href=[''"](.*?)[''"][^>]*?>(.*?)<'/a>/si';
  preg_match_all($href_regex_pattern,$html,$matches);
  if (count($matches)) {
    if (is_array($matches[$argument]) && count($matches[$argument])) {
      return $matches[$argument][0];
    }
    return $matches[1];
  } else 
function getTags( $dom, $tagName, $element = false, $children = false ) {
    $html = '';
    $domxpath = new DOMXPath($dom);
    $children = ($children) ? "/".$children : '';  
    $filtered = $domxpath->query("//$tagName" . $children);
    $i = 0;
    while( $myItem = $filtered->item($i++) ){
        $newDom = new DOMDocument;
        $newDom->formatOutput = true;        
        $node = $newDom->importNode( $myItem, true );
        $newDom->appendChild($node);
        $html[] = $newDom->saveHTML();          
    }
    if ($element !== false && isset($html[$element])) {
      return $html[$element];
    } else
      return $html;
} 

您可以使用strpos($html, 'href='),然后解析URL。您也可以搜索<a.php