Last active
January 27, 2021 14:47
-
-
Save svandragt/0676d08452aa368172946a2b7afcbc3c to your computer and use it in GitHub Desktop.
phpquery maintainable demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace SvanDragt\Test; | |
require_once __DIR__ . '/vendor/autoload.php'; | |
use phpQuery; | |
function do_parse() { | |
// INITIALIZE IT | |
// phpQuery::newDocumentHTML($markup); | |
// phpQuery::newDocumentXML(); | |
// phpQuery::newDocumentFileXHTML('test.html'); | |
// phpQuery::newDocumentFilePHP('test.php'); | |
// phpQuery::newDocument('test.xml', 'application/rss+xml'); | |
// this one defaults to text/html in utf8 | |
$doc = phpQuery::newDocument('<div/>'); | |
// FILL IT | |
// array syntax works like ->find() here | |
$doc['div']->append('<ul></ul>'); | |
// array set changes inner html | |
$doc['div ul'] = '<li>1</li> <li>2</li> <li>3</li>'; | |
// MANIPULATE IT | |
$li = null; | |
// almost everything can be a chain | |
$doc['ul > li'] | |
->addClass('my-new-class') | |
->filter(':last') | |
->addClass('last-li') | |
// save it anywhere in the chain | |
->toReference($li); | |
// ITERATE IT | |
// all direct LIs from $ul | |
foreach($doc['ul > li'] as $li) { | |
// iteration returns PLAIN dom nodes, NOT phpQuery objects | |
$tagName = $li->tagName; | |
$childNodes = $li->childNodes; | |
// so you NEED to wrap it within phpQuery | |
phpQuery::newDocument($li)->addClass('my-second-new-class'); | |
// | |
} | |
$doc['ul > li']->addClass('my-third-new-class'); | |
return $doc; | |
} | |
$doc = do_parse(); | |
// PRINT OUTPUT | |
// 1st way | |
print "<h3>first</h3>"; | |
print phpQuery::getDocument($doc->getDocumentID()); | |
// 2th way | |
print "<h3>fourth</h3>"; | |
print $doc->htmlOuter(); | |
// 3th way | |
print "<h3>fifth</h3>"; | |
print $doc; | |
// another... | |
print "<h3>sixth</h3>"; | |
print $doc['ul']; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Basically avoid
pq()
, and any global state by returning phpQueryObjects from functions.