PHP DOMDocument,查找特定元素 [英] PHP DOMDocument, finding specific elements

查看:372
本文介绍了PHP DOMDocument,查找特定元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用PHP DOMDocument在HTML文档中找到特定元素的特定属性.

I'm looking to find a specific attribute of a specific element in an HTML document using PHP DOMDocument.

具体来说,有一个div,它具有唯一的类集,并且其中只有一个跨度.我需要检索该span元素的style属性.

Specifically, there is a div with a unique class set, and only a single span inside of it. I need to retrieve the style attribute of that span element.

示例:

<div class="uniqueClass"><span style="text-align: center;" /></div>

在此示例中,uniqueClass是文档中该类的唯一实例,我需要检索字符串:

For this example, with the uniqueClass being the only instance of that class in the document, I would need to retrieve the string:

text-align:center;

text-align: center;

推荐答案

您必须使用DOMXPAth类

You have to use DOMXPAth class

$doc = new DOMDocument; 
// We don't want to bother with white spaces
$doc->preserveWhiteSpace = false;

$doc->loadHTML($htmlSource);

$xpath = new DOMXPath($doc);

// We starts from the root element
$query = '//div[@class= uniqueClass]/span';

$entries = $xpath->query($query);

$spanStyle = $entries->current()->getAttribute('style')

这篇关于PHP DOMDocument,查找特定元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆