【问题标题】:Parsing an image using simple DOM使用简单的 DOM 解析图像
【发布时间】:2014-11-27 08:41:23
【问题描述】:

我想使用简单的 dom 从 HTML 文件中解析图像。直到现在我都在使用正则表达式,但每个人都告诉我这是一个非常糟糕的主意,所以我想尝试 dom。

<?php
include('simple_html_dom.php');
$html = file_get_html('192.0.0.1/test.html');
var_dump($html);
foreach ($html->find('img') as $image) {
    echo $images->src;
}
?>

TEST.html

<html>
<head>
</head>
<body>
    <p>test</p>
    <img src="test.jpg"/>
    <p>test1</p>
</body>
</html>

我得到一个空白页,我检查了错误日志,但我没有。我按照关于 DOM 的教程进行操作,是不是搞错了?

我还可以从具有 HTML 代码的变量中解析 img 吗? 我的意思:

$string='<p>sdadasd</p> <img src="test.jph/> <p>asdasda</p>';
$html=file_get_hmtl($string);

【问题讨论】:

  • 我不知道那是什么:D
  • 请使用 var_dump($image); 检查变量 $image 包含的内容;
  • 图片没有hrefs
  • 奇怪的是输出从空白变成了这个:find('img') as $image) { echo $images->href; var_dump($images); } ?> 这就像在 foreach ($html-> :S
  • @musa 我完全重启了.. 我应该在实习 9 小时后停止编码。我想解析 src 而不是 href :S

标签: php html simpledom


【解决方案1】:

你可以使用这样的东西(我不知道你从哪里得到file_get_html,所以我不知道该对象返回什么方法)

$document = new DOMDocument();
$document->loadHTMLFile("http://127.0.0.1/index.html"); // I don't remember if this accepts streams

$images = $document->getElementsByTagName("img");

foreach($images as $image) {
    //Use the image
}

或者,如果您需要复杂的查询(例如具有特定属性的 img 标签),您可以这样做

$xpath = new DOMXPath($document);
$images = $xpath->query("//img");

【讨论】:

  • 我得到这个:警告:DOMDocument::loadHTMLFile(): I/O 警告:未能加载外部实体“127.0.0.1/yolo.html”在 C:\wamp\www\test.php 第 3 行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多