Skip to content Skip to sidebar Skip to footer

Php - How Can I Retrieve A Div Tag Attribute Value

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 p

Solution 1:

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 ($entriesas$entry) {
  echo"Found: " . $entry->getAttribute("attrloc");
}

Hope it helps!

Solution 2:

Using jQuery in JavaScript

var state = $('#btn-loc').attr('attrLoc');

Then you can send the value to PHP

EDIT:

If you are working with an HTML page/DOM in PHP you can use SimpleXML to traverse the DOM and pull your attributes that way

$xml = simplexml_load_string(
    '<div id="btn-loc" class="hidden" attrLoc="1">
    ...
    </div>'
);

foreach (current($xml->xpath('/*/div'))->attributes() as$k => $v)
{
    var_dump($k,' : ',$v,'<br />');
}

You will see the name and the value of the attributes dumped

id :btn-locclass :hiddenattrLoc :1

Solution 3:

You can also use Document Object Model

<?php$str = '<div id="btn-loc" class="hidden" attrLoc="1">
text
</div>';
$doc = new DOMDocument();
$d=$doc->loadHtml($str);
$a = $doc->getElementById('btn-loc');
var_dump($a->getAttribute('attrloc'));

Solution 4:

to do this with php use simple html dom parser. has a bit of learning curve, but kind of useful

http://simplehtmldom.sourceforge.net/

Solution 5:

How about this

$str = '<div id="btn-loc" class="hidden" attrLoc="1">';
$pattern = '/<div id="btn-loc".*\sattrLoc="([0-9])">/';
preg_match($pattern, $str, $matches);
var_dump($matches);

Outputs

array0 => string'<div id="btn-loc" class="hidden" attrLoc="1">' (length=45)  
  1 => string'1' (length=1)

Post a Comment for "Php - How Can I Retrieve A Div Tag Attribute Value"