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!
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
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'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With