Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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>
like image 747
Marc Avatar asked Feb 28 '12 08:02

Marc


3 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!

like image 82
Tom Desp Avatar answered Oct 19 '22 11:10

Tom Desp


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
like image 24
darryn.ten Avatar answered Oct 19 '22 09:10

darryn.ten


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'));
like image 25
Kuba Avatar answered Oct 19 '22 10:10

Kuba