Php - how can I get the value of a div tag attribute

I have a div that can be hidden or not, depending on the user. This div has the attribute "attrLoc". I would like it to be impossible to get this attribute value from php. Hope someone can help. Thank you in advance for your answers. Greetings. Mark.

My HTML:

<div id="btn-loc" class="hidden" attrLoc="1"> ... </div> 
+6
source share
5 answers

XPath is the standard for querying XML structures .

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

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 this helps!

+7
source

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 move the DOM and pull out your attributes this 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 value of the reset attributes

 id : btn-loc class : hidden attrLoc : 1 
+4
source

You can also use the 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')); 
+2
source

to do this with php using a simple html dom parser. has a little learning curve but kind of useful

http://simplehtmldom.sourceforge.net/

+1
source

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) 
0
source

Source: https://habr.com/ru/post/909525/


All Articles