PHP code example of stil / xpath-selector

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

    

stil / xpath-selector example snippets


use XPathSelector\Selector;
$xs = Selector::load($pathToXml);
$xs = Selector::loadHTMLFile($pathToHtml);
$xs = Selector::loadXML($xmlString);
$xs = Selector::loadHTML($htmlString);

use XPathSelector\Exception\NodeNotFoundException;

try {
	$element = $xs->find('//head'); // returns first <head> element found
	echo $element->innerHTML(); // print innerHTML of <head> tag
} catch (NodeNotFoundException $e) {
	echo $e->getMessage(); // nothing have been found
}

use XPathSelector\Selector;

$urls = $xs->findAll('//a/@href');
foreach ($urls as $url) {
	echo $url;
}

use XPathSelector\Selector;

$doesExist = $xs->findOneOrNull('//a/@href') !== null;


use XPathSelector\Selector;
$xs = Selector::load('sample.xml');

echo $xs->find('/bookstore/book[1]/title');


use XPathSelector\Selector;
$xs = Selector::load('sample.xml');

foreach ($xs->findAll('/bookstore/book') as $book) {
	printf(
		"[Title: %s][Price: %s]\n",
		$book->find('title')->extract(),
		$book->find('price')->extract()
	);
}


use XPathSelector\Selector;
$xs = Selector::load('sample.xml');

$array = $xs->findAll('/bookstore/book')->map(function ($node, $index) {
	return [
		'index' => $index,
		'title' => $node->find('title')->extract(),
		'price' => (float)$node->find('price')->extract()
	];
});

var_dump($array);