【问题标题】:how to get single out put from image tag with simplexml_import_dom?如何使用 simplexml_import_dom 从图像标签中获取单个输出?
【发布时间】:2017-11-25 07:33:32
【问题描述】:

我已经使用下面的代码从网页中提取了图像,但我只想获取数据中的第二个“图像”和“alt”。

"image: /images/2.png
Alt : image 2"

任何帮助将不胜感激。

@$dom->loadHTML($page);
    
$xml = simplexml_import_dom($dom);
    
    $images = $xml->xpath('//img');
    
    foreach ($images as $img) {
        
        if (isset($img["src"]) && isset($img["alt"])) 
            echo "image: " . $img['src'] . "<br />";
            echo "Alt : " . $img['alt'] . "<br />";
    
    }

返回:

image: /images/1.png
Alt : image 1

image: /images/2.png
Alt : image 2

image: /images/3.png
Alt : image 3

【问题讨论】:

    标签: php dom xpath simplexml


    【解决方案1】:

    xpath 返回一个数组,所以$images 是一个数组 您可以访问第二个元素,例如 $images[1]

    $images[1] 的类型为 SimpleXMLElement,您可以访问以下属性:

    $src = $images[1]->attributes()->src;
    $alt = $images[1]->attributes()->alt;
    if ($src && $alt) {
        echo "image: " . $src . "<br />";
        echo "Alt : " . $alt . "<br />";
    }
    

    或者您可以将 xpath 表达式更新为:

    $images = $xml->xpath('//img[2]');
    
    if (isset($images[0])) {
        // etc ..
    }
    

    【讨论】:

      猜你喜欢
      • 2017-11-07
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-20
      • 1970-01-01
      相关资源
      最近更新 更多