PHP的 - 如何检索div标签属性值 [英] php - how can I retrieve a div tag attribute value

查看:127
本文介绍了PHP的 - 如何检索div标签属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以隐藏或不隐藏的div,具体取决于用户。该div有一个名为'attrLoc'的属性。我希望能够从php中检索该属性值。希望有人能帮忙。预先感谢您的回复。干杯。 Marc。



我的HTML:

 < div id = btn-locclass =hiddenattrLoc =1> 
...
< / div>


解决方案

XPath 查询XML结构的标准。然而,请注意,如果你想从一个不受信任的源代码解析HTML,那么这个源代码的HTML并不是非常完整的,你应该更喜欢 http://www.php.net/manual/en/domdocument.loadhtml.phprel =noreferrer> DOMDocument :: loadHTML() SimpleXML 变体,特别是 simplexml_load_string



举例

 <?php 
$ html ='
< div id =btn-locclass =hiddenattrLoc =1>
...
< / div>';

$ doc = DOMDocument :: loadHTML($ html);
$ xpath = new DOMXPath($ doc);
$ query =// div [@ id ='btn-loc'];
$ entries = $ xpath-> query($ query);
foreach($条目为$条目){
echoFound:。 $入门>的getAttribute( attrloc);
}

希望它有帮助!


I have a div which can be hidden or not, depending on the user. That div has an attribute called 'attrLoc'. What I would like is to be abble to retrieve that attribute value from php. Hope someone can help. Thank you in advance for your replies. Cheers. Marc.

My HTML:

<div id="btn-loc" class="hidden" attrLoc="1">
...
</div>

解决方案

XPath is quite the standard for querying XML structures.

However, note that if you want to parse HTML from an untrusted source, that is a source where HTML is not absolutely well formed, you should prefer DOMDocument::loadHTML() to SimpleXML variants, in particular simplexml_load_string.

For Example

<?php
$html = '
<div id="btn-loc" class="hidden" attrLoc="1">
  ...
</div>';

$doc = DOMDocument::loadHTML($html);
$xpath = new DOMXPath($doc);
$query = "//div[@id='btn-loc']";
$entries = $xpath->query($query);
foreach ($entries as $entry) {
  echo "Found: " . $entry->getAttribute("attrloc");
}

Hope it helps!

这篇关于PHP的 - 如何检索div标签属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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