symfony/DomCrawler — pull request #15 by srcspider (2013-08-29 12:20:52+00:00)
Title: Hotfix for HTML form attribute handling

The following,

$form = $node->ownerDocument->getElementById($formId);

...is an unreliable way to retrieve the ID.

Even if there is an element with an id attribute the id won't be recognized unless the document was validated at the point it was read which in the case of setNode (for whatever reason) does not happen under some circumstances.

To give an example, given the following xml file

And the following code,

validateOnParse = true;
$doc->Load('test.xml');

echo 'Form Tag Exists? '.($doc->getElementById('testform1') === null ? 'Nope' : 'Yup');

The code will still output "Form Tag Exists? Nope" because of how picky the getElementById method is.

For more on the phenomenon see this stackoverflow answer: http://stackoverflow.com/questions/3391942/php-html-domdocument-getelementbyid-problems

I haven't been able to track down why the document in question doesn't work with getElementById, but somehow I'm assuming it has something to do with html5 not having a DTD (though for what it's worth ownerDocument in that particular case somehow gets reduced to just the form and the fields; which is weird in of itself). For reference the real world circumstances where this borks miserably is when using behat with goutte.

The following XPath version appears to reliably work,

$xp = new \DOMXPath($node->ownerDocument);
$form = $xp->query("//*[@id='{$formId}']")->item(0);