Home » Php » html – php – how can I retrieve a div tag attribute value

html – php – how can I retrieve a div tag attribute value

Posted by: admin July 12, 2020 Leave a comment

Questions:

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>
How to&Answers:

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!

Answer:

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-loc
class : hidden
attrLoc : 1

Answer:

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'));

Answer:

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

http://simplehtmldom.sourceforge.net/

Answer:

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

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