Skip to content

Instantly share code, notes, and snippets.

@svandragt
Last active January 27, 2021 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save svandragt/0676d08452aa368172946a2b7afcbc3c to your computer and use it in GitHub Desktop.
Save svandragt/0676d08452aa368172946a2b7afcbc3c to your computer and use it in GitHub Desktop.
phpquery maintainable demo
<?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'];
@svandragt
Copy link
Author

Basically avoid pq(), and any global state by returning phpQueryObjects from functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment