In this particular, How to Get HTML Tag Value in PHP, article we will use the PHP DOMDocument Class which represents the HTML or XML document and also serves as the root of the document tree.
Here we discuss 4 tasks where we use the PHP DOMDocument class to get the value of HTML tags,
- How to get a paragraph
<p>
tag value using PHP - How to get
<span>
tag value using PHP - How to store
<span>
value in PHP - How to access HTML elements in PHP
How to get a paragraph <p>
tag value using PHP
In the below example How to get p tag value using PHP, we create a paragraph with an HTML ID attribute and set the text inside the P tag.
1 2 3 4 5 6 |
<?php $htmlEle = "<p id='paraID'>Paragraph Sports</span>"; $domdoc = new DOMDocument(); $domdoc->loadHTML($htmlEle); echo $domdoc->getElementById('paraID')->nodeValue; |
Output: Paragraph Sports
Code Explanations:
- Using the PHP DOMDocument Class, call the DOMDocument object.
- Call the predefined
loadHTML()
function with variable parameters. - Using the
getElementById()
DOM function we get the HTML element value.
How to get <span>
tag value using PHP
1 2 3 4 5 6 |
<?php $htmlEle = "<span id='SpanID'>Span Sports</span>"; $domdoc = new DOMDocument(); $domdoc->loadHTML($htmlEle); echo $domdoc->getElementById('SpanID')->nodeValue; |
Output: Span Sports
This is also the same process as the code with the changed ID.
How to Store span Value in PHP
If you want to store only span value then do the same code and create a variable on the last and assign the previous value that you get using PHP DOMDocument.
1 2 3 4 5 6 7 8 9 |
<?php $htmlEle = "<span id='SpanID'>Span Sports</span>"; $domdoc = new DOMDocument(); $domdoc->loadHTML($htmlEle); $spanValue = $domdoc->getElementById('SpanID')->nodeValue; <strong>//Store span Value in PHP variable</strong> echo $spanValue; |
Output: Span Sports
How to Access HTML Elements in PHP
Here is a complete quick summary of how to get Html tag value in PHP or access HTML elements,
- getElementsByTagName(‘a’)
- getElementById(‘SpanID’)
For more, you can check on the official’s site, https://www.php.net/manual/en/class.domdocument.php
Here is a complete reference about accessing the HTML element in PHP with an example.
Also Check:
- How to Convert JSON to Array PHP
- How to Store Data In Cookies Using JavaScript
- Steps to Upload Multiple Images in PHP with Preview
- Multiple Barcode Generator in PHP
Happy Coding..!
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] How to Get HTML Tag Value in PHP […]
[…] found the above snippet on https://codingtasks.net/how-to-get-html-tag-value-in-php/ and modified it as per my need but did not […]