【问题标题】:How to get the src of images php如何获取图像的src php
【发布时间】:2014-07-10 08:50:29
【问题描述】:

所以我有大量的 html 图像,id 为 images。一个例子是这样的:

<img id="images" src="video images/the wind rises.jpg" alt="" width="700" height="525" class="the-wind-rises1" />

我想收集所有的 src(例如video images/the wind rises.jpg) 我试过这个。但它不工作怎么来的?:

<?php
$html = file_get_contents('http://urlofwebsite.co.uk/xxxx');

function linkExtractor($html){
    $imageArr = array();
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $images = $doc->getElementById('images');
    foreach($images as $image) {
        array_push($imageArr, $image->getAttribute('src'));
    }
    return $imageArr;
}

echo json_encode(array("images" => linkExtractor($html)));
?>

它只是返回:

{"images":[]}

【问题讨论】:

  • 首先,任何给定的id 只能合法地拥有一个元素,所以这总是令人讨厌的。其次,使用@ 几乎不是一个好主意。
  • 或者你可以使用getbytag $doc-&gt;getElementsByTagName('img');
  • @lonesomeday 有时你需要它。例如,如果您正在解析数据,并且不想向前端(用户)发送警告。但是你应该检查所有时间,如果它成功,如果没有实现自定义错误处理 (throw new XmlNotValidException())
  • @ChristianGollhardt 为什么在生产服务器上启用了错误消息?
  • @lonesomeday 那不是,我说过的。但是,如果您的应用程序的状态不是您期望的状态,您为什么要继续?当然在生产使用中,我要么看不到警告,但我是否应该在开发阶段看到这么多警告,以至于我看不到我感兴趣的警告?如果自己做一些异常处理,用@感觉不错

标签: php html json


【解决方案1】:

您正在使用getElementById,并且此函数应该返回一个元素或 null 看看:http://www.php.net/manual/en/domdocument.getelementbyid.php

我会说尝试以下方法:

$image = $doc->getElementById('images');
return $image->getAttribute('src');

如果您的目的是收集所有图像的来源,那么您将不得不使用 getElementsByTagName : http://www.php.net/manual/en/domdocument.getelementsbytagname.php

function linkExtractor($html){
    $imageArr = array();
    $doc = new DOMDocument();
    @$doc->loadHTML($html);
    $images = $doc->getElementsByTagName('img');
    foreach($images as $image) {
        array_push($imageArr, $image->getAttribute('src'));
    }
    return $imageArr;
}

【讨论】:

  • 我的目的是收集所有ID为images的图像的来源
  • in html id 属性应该是唯一的,您可以在 html 中使用 class 代替。请阅读w3.org/TR/html401/struct/global.html#h-7.5.2的id部分
  • 我尝试了这个,我将 id 更改为类,但我收到错误 Call to undefined method DOMDocument::getElementByClass()
  • 我在DOMDocument API 页面中没有看到任何名为getElementsByClass 的函数,我会说你有两个选择:要么通过 TagName 循环获取所有元素,然后选择那些有 className = 'images' 或其他选项是使用像这篇文章中的选择器:stackoverflow.com/questions/6366351/…
  • 如何通过 TagName 循环获取所有元素,然后只选择具有 className = 'images' 的元素??
【解决方案2】:

因为 ID 是(应该)唯一的,所以它只返回一个元素

$images = $doc->getElementById('images');
array_push($imageArr, $images->getAttribute('src'));

文档:http://www.php.net/manual/en/domdocument.getelementbyid.php

【讨论】:

    猜你喜欢
    • 2019-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-04
    • 1970-01-01
    • 2011-04-25
    • 1970-01-01
    • 2019-06-13
    相关资源
    最近更新 更多