关于`file_get_html`的2个问题

时间:2011-03-08 19:36:27

标签: php html dom

我想使用simple_html_dom.php做一些工作。

$html = file_get_html('http://www.domain.com');
foreach($html->find('p') as $element) {
echo $element;
}

我有两个问题。

  1. 如果failed to open stream:然后echo 'this is not a valid url';
  2. ,如何添加评委
  3. 如果p中没有foreach标记,那么如何判断echo 'Can not find p tag';
  4. 感谢。

3 个答案:

答案 0 :(得分:3)

这是问题的一部分Simple_HTML_DOM ... file_get_html()始终返回有效对象,无论加载是否失败。创建自己的实例也没有帮助......没有实际的方法可以知道你的文件是否正确解析。

至于确定结果中是否确实有<p>个元素:

$pTags = $html->find('p');

if(empty($pTags)) {
  echo 'Cannot find p tag';
} else {
  foreach($pTags as $element) {
    echo $element;
  }
}

总的来说,我建议删除Simple_HTML_DOM并将您的代码迁移到phpQuery(从正面看,phpQuery不进行自己的解析,它只是一个包装器PHP的DOMDocument类)。 API更加简化,可以让您知道解析是否成功。

try {
  $html = phpQuery::newDocument($sourceCode);

  $pTags = $html->find('p');

  if(empty($pTags)) {
    echo 'Cannot find p tag';
  } else {
    foreach($pTags as $element) {
      $element = pq($element); // Wrap raw DOMNode in phpQuery object instance;
      echo $element->html();
    }
  }
} catch(Exception $ex) {
  echo $ex->getMessage();
}

答案 1 :(得分:0)

试试这个:

$html = file_get_html('http://www.domain.com') or die('this is not a valid url');
$p = $html->find('p');
if(count($p) <=0){
   die('Can not find p tag')
}
foreach($p as $element) {
echo $element;
}

答案 2 :(得分:0)

$html = new Simple_html_dom();
$ipaddrss='write your url here';
$html = file_get_html($ipaddrss);
$anchor=$html->find('dd[class=count]');//you can find the tags with its attributes like 
//shown here
if($anchor) {
    echo $anchor;
} else {
    echo "sorry! no tags found";
}