1. Go to this page and download the library: Download xinningsu/html-query library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
xinningsu / html-query example snippets
use Sulao\HtmlQuery\HQ;
$html = '
<html>
<head>
<title>Html Query</title>
</head>
<body>
<h1 class="title">this is title</h1>
<div class="content">this is <b>content</b>...</div>
</body>
</html>
';
$hq = HQ::html($html);
echo $hq('.title')->html();
//this is title
echo $hq('.content')->html();
//this is <b>content</b>...
echo $hq('.content')->outerHtml();
//<div class="content">this is <b>content</b>...</div>
echo $hq('.content')->text();
//this is content...
$html = '
<html>
<head>
<title>Html Query</title>
</head>
<body>
<h1 class="title">this is title</h1>
<div class="content">this is <b>content</b>...</div>
</body>
</html>
';
$hq = HQ::html($html);
echo $hq('.title')->html('this is new title')->html();
//this is new title
echo $hq('.content')->html('this is <b>new content</b>...')->html();
//this is <b>new content</b>...
echo $hq('.content')->text('this is new content...')->html();
//this is new content...
use Sulao\HtmlQuery\{HQ, HtmlQuery};
$html = '
<div class="container">
<img src="1.png">
<img src="2.png">
<div class="img">
<img src="3.png">
</div>
</div>
';
$hq = HQ::html($html);
$images = $hq('.container img')->map(function (DOMElement $node) {
return $node->getAttribute('src');
});
print_r($images);
//['1.png', '2.png', '3.png']
// or resolve the DOMElement to HtmlQuery instance by type hinting
$images = $hq('.container img')->map(function (HtmlQuery $node) {
return $node->attr('src');
});
print_r($images);
//['1.png', '2.png', '3.png']
// Specified which node
echo $hq('.container img')->eq(1)->attr('src');
//2.png
// Or access the DOMNode like array
echo $hq('.container img')[1]->getAttribute('src');
//2.png