How to jQuery on PHP
How to jQuery on PHP, seems to be an odd question but if you think about it, it is actually very useful. Imagine you can just get data inside html string just like jQuery, parsing will be a lot easier.
Okay, now let’s just get this straight. This is not possible, but there is one PHP library that you can use help you parse HTML strings.
You can use PHP HTML Parser, very easy to use and has great documentation. Below are some sample codes from their docs.
// Assuming you installed from Composer:
require "vendor/autoload.php";
use PHPHtmlParser\Dom;
$dom = new Dom;
$dom->loadStr('<div class="all"><p>Hey bro, <a href="google.com">click here</a><br /> :)</p></div>');
$a = $dom->find('a')[0];
echo $a->text; // "click here"
Assuming that you have enough experience on PHP and you know jQuery. You should be able to see the resemblance of the codes of jQuery and PHP. This is very helpful specially if you have a project that requires complex design from a source that has no API. And the only source you have is the web pages of some external websites or internal web pages.
Another more complex code sample. Below, the code is for parsing external sources. It will technically converts the external source to string first, this part is tricky because there will be cases that you might not be able to parse a web page for various reasons.
Some of these reasons are:
- The Page is secure and not open for any external fetching. This usually gives 403 headers.
- There are special characters that cannot be parsed by the library.
- The page is loaded via ajax or same asynchronous scripts.
// Assuming you installed from Composer:
require "vendor/autoload.php";
use PHPHtmlParser\Dom;
$dom = new Dom;
$dom->loadFromFile('tests/data/big.html');
$contents = $dom->find('.content-border');
echo count($contents); // 10
foreach ($contents as $content)
{
// get the class attr
$class = $content->getAttribute('class');
// do something with the html
$html = $content->innerHtml;
// or refine the find some more
$child = $content->firstChild();
$sibling = $child->nextSibling();
}
You can also parse from external sources. This may load a little slower since you are actually fetching render blocking source but the idea is there. You can modify it to fits the requirement of your project.
That’s it, Of course there are other ways, but it wouldn’t hurt to know one more option for your projects. Good Luck!