PHP code example of diffen / justhtml

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

    

diffen / justhtml example snippets




ustHTML\JustHTML;

$html = '<article><h1>Title</h1><p class="lead">Earth is a <a href="/planet">planet</a>.</p></article>';
$doc = new JustHTML($html);

$title = $doc->queryFirst('h1');
$lead = $doc->queryFirst('p.lead');

if ($title === null || $lead === null) {
    throw new RuntimeException('Expected content was not found');
}

echo $title->toText() . "\n";
echo $lead->toText() . "\n";

$html = <<<'HTML'
<p id="lead">
  Earth is a <a href="/planet">planet</a>.
</p>
HTML;

$doc = new JustHTML($html);
$node = $doc->queryFirst('#lead');

if ($node === null) {
    throw new RuntimeException('Lead paragraph was not found');
}

echo $node->toText() . "\n";
echo json_encode($node->textContent) . "\n";

$nodes = $doc->query('main p'); // CSS selector query; returns matching nodes
$first = $doc->queryFirst('main p'); // First match or null
echo $nodes[0]->toText() . "\n";
echo ($nodes[0]->matches('main > p') ? 'true' : 'false') . "\n"; // CSS selector match on this node
echo ($nodes[0]->matches('article p') ? 'true' : 'false') . "\n"; // true/false based on selector match

$nodes = $doc->query('main p, main a'); // Multiple selectors
echo count($nodes) . "\n";

$markdown = $doc->toMarkdown();

use JustHTML\Stream;

foreach (Stream::select($html, '#mw-content-text p') as $paragraph) {
    $text = $paragraph->toText();
    if ($text !== '') {
        echo $text;
        break;
    }
}

$title = Stream::selectFirst($html, 'main > h1');
sh
php examples/wikipedia_earth_demo.php
sh
git submodule update --init --recursive
php run_tests.php