PHP code example of edwinhuish / domquery

1. Go to this page and download the library: Download edwinhuish/domquery 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/ */

    

edwinhuish / domquery example snippets


DomQuery::create('<a title="hello"></a>')->attr('title') // hello

$dom->find('namespace\\:h1')->text();
 php
$dom = new DomQuery('<div><h1 class="title">Hello</h1></div>');

echo $dom->find('h1')->text(); // output: Hello
echo $dom->find('div')->prop('outerHTML'); // output: <div><h1 class="title">Hello</h1></div>
echo $dom->find('div')->html(); // output: <h1 class="title">Hello</h1>
echo $dom->find('div > h1')->class; // output: title
echo $dom->find('div > h1')->attr('class'); // output: title
echo $dom->find('div > h1')->prop('tagName'); // output: h1
echo $dom->find('div')->children('h1')->prop('tagName'); // output: h1
echo (string) $dom->find('div > h1'); // output: <h1 class="title">Hello</h1>
echo count($dom->find('div, h1')); // output: 2
 php
$dom = new DomQuery('<a>1</a> <a>2</a> <a>3</a>');
$links = $dom->children('a');

// foreach
$texts = [];
foreach($links as $key => $dq) { // $dq is DomQuery object
    $texts[] = $dq->text();
}
print_r($texts); // array('1','2','3')

// map 
$result = $links->map(function(DomQuery $dq, int $idx){
    return $dq->text();
});
// map method return Collection object
print_r($result->toArray()); // array('1','2','3')

// each, same as Collection's each method, break traversing if return false.
$links->each(function(DomQuery $dq, int $idx){
    if($idx === 1){
        return false;
    }
    $dq->text('changed');
});
print_r($links->texts()); // array('changed', '2', '3')

echo $links->text(); // output 1, return text of first child, if you need the result of all childs please use texts() or foreach, each, map method
echo $links[0]->text(); // output 1
echo $links->last()->text(); // output 3
echo $links->first()->next()->text(); // output 2
echo $links->last()->prev()->text(); // output 2
echo $links->get(0)->textContent; // output 1
echo $links->get(-1)->textContent; // output 3