4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\DomCrawler;
14 use Symfony\Component\CssSelector\CssSelectorConverter;
17 * Crawler eases navigation of a list of \DOMNode objects.
19 * @author Fabien Potencier <fabien@symfony.com>
21 class Crawler implements \Countable, \IteratorAggregate
24 * @var string The current URI
29 * @var string The default namespace prefix to be used with XPath and CSS expressions
31 private $defaultNamespacePrefix = 'default';
34 * @var array A map of manually registered namespaces
36 private $namespaces = array();
39 * @var string The base href value
44 * @var \DOMDocument|null
51 private $nodes = array();
54 * Whether the Crawler contains HTML or XML content (used when converting CSS to XPath).
58 private $isHtml = true;
61 * @param mixed $node A Node to use as the base for the crawling
62 * @param string $currentUri The current URI
63 * @param string $baseHref The base href value
65 public function __construct($node = null, $currentUri = null, $baseHref = null)
67 $this->uri = $currentUri;
68 $this->baseHref = $baseHref ?: $currentUri;
74 * Returns the current URI.
78 public function getUri()
88 public function getBaseHref()
90 return $this->baseHref;
94 * Removes all the nodes.
96 public function clear()
98 $this->nodes = array();
99 $this->document = null;
103 * Adds a node to the current list of nodes.
105 * This method uses the appropriate specialized add*() method based
106 * on the type of the argument.
108 * @param \DOMNodeList|\DOMNode|array|string|null $node A node
110 * @throws \InvalidArgumentException When node is not the expected type.
112 public function add($node)
114 if ($node instanceof \DOMNodeList) {
115 $this->addNodeList($node);
116 } elseif ($node instanceof \DOMNode) {
117 $this->addNode($node);
118 } elseif (is_array($node)) {
119 $this->addNodes($node);
120 } elseif (is_string($node)) {
121 $this->addContent($node);
122 } elseif (null !== $node) {
123 throw new \InvalidArgumentException(sprintf('Expecting a DOMNodeList or DOMNode instance, an array, a string, or null, but got "%s".', is_object($node) ? get_class($node) : gettype($node)));
128 * Adds HTML/XML content.
130 * If the charset is not set via the content type, it is assumed
131 * to be ISO-8859-1, which is the default charset defined by the
132 * HTTP 1.1 specification.
134 * @param string $content A string to parse as HTML/XML
135 * @param null|string $type The content type of the string
137 public function addContent($content, $type = null)
140 $type = 0 === strpos($content, '<?xml') ? 'application/xml' : 'text/html';
143 // DOM only for HTML/XML content
144 if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
149 if (false !== $pos = stripos($type, 'charset=')) {
150 $charset = substr($type, $pos + 8);
151 if (false !== $pos = strpos($charset, ';')) {
152 $charset = substr($charset, 0, $pos);
156 // http://www.w3.org/TR/encoding/#encodings
157 // http://www.w3.org/TR/REC-xml/#NT-EncName
158 if (null === $charset &&
159 preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9_:.]+)/i', $content, $matches)) {
160 $charset = $matches[1];
163 if (null === $charset) {
164 $charset = 'ISO-8859-1';
167 if ('x' === $xmlMatches[1]) {
168 $this->addXmlContent($content, $charset);
170 $this->addHtmlContent($content, $charset);
175 * Adds an HTML content to the list of nodes.
177 * The libxml errors are disabled when the content is parsed.
179 * If you want to get parsing errors, be sure to enable
180 * internal errors via libxml_use_internal_errors(true)
181 * and then, get the errors via libxml_get_errors(). Be
182 * sure to clear errors with libxml_clear_errors() afterward.
184 * @param string $content The HTML content
185 * @param string $charset The charset
187 public function addHtmlContent($content, $charset = 'UTF-8')
189 $internalErrors = libxml_use_internal_errors(true);
190 $disableEntities = libxml_disable_entity_loader(true);
192 $dom = new \DOMDocument('1.0', $charset);
193 $dom->validateOnParse = true;
195 set_error_handler(function () { throw new \Exception(); });
198 // Convert charset to HTML-entities to work around bugs in DOMDocument::loadHTML()
199 $content = mb_convert_encoding($content, 'HTML-ENTITIES', $charset);
200 } catch (\Exception $e) {
203 restore_error_handler();
205 if ('' !== trim($content)) {
206 @$dom->loadHTML($content);
209 libxml_use_internal_errors($internalErrors);
210 libxml_disable_entity_loader($disableEntities);
212 $this->addDocument($dom);
214 $base = $this->filterRelativeXPath('descendant-or-self::base')->extract(array('href'));
216 $baseHref = current($base);
217 if (count($base) && !empty($baseHref)) {
218 if ($this->baseHref) {
219 $linkNode = $dom->createElement('a');
220 $linkNode->setAttribute('href', $baseHref);
221 $link = new Link($linkNode, $this->baseHref);
222 $this->baseHref = $link->getUri();
224 $this->baseHref = $baseHref;
230 * Adds an XML content to the list of nodes.
232 * The libxml errors are disabled when the content is parsed.
234 * If you want to get parsing errors, be sure to enable
235 * internal errors via libxml_use_internal_errors(true)
236 * and then, get the errors via libxml_get_errors(). Be
237 * sure to clear errors with libxml_clear_errors() afterward.
239 * @param string $content The XML content
240 * @param string $charset The charset
241 * @param int $options Bitwise OR of the libxml option constants
242 * LIBXML_PARSEHUGE is dangerous, see
243 * http://symfony.com/blog/security-release-symfony-2-0-17-released
245 public function addXmlContent($content, $charset = 'UTF-8', $options = LIBXML_NONET)
247 // remove the default namespace if it's the only namespace to make XPath expressions simpler
248 if (!preg_match('/xmlns:/', $content)) {
249 $content = str_replace('xmlns', 'ns', $content);
252 $internalErrors = libxml_use_internal_errors(true);
253 $disableEntities = libxml_disable_entity_loader(true);
255 $dom = new \DOMDocument('1.0', $charset);
256 $dom->validateOnParse = true;
258 if ('' !== trim($content)) {
259 @$dom->loadXML($content, $options);
262 libxml_use_internal_errors($internalErrors);
263 libxml_disable_entity_loader($disableEntities);
265 $this->addDocument($dom);
267 $this->isHtml = false;
271 * Adds a \DOMDocument to the list of nodes.
273 * @param \DOMDocument $dom A \DOMDocument instance
275 public function addDocument(\DOMDocument $dom)
277 if ($dom->documentElement) {
278 $this->addNode($dom->documentElement);
283 * Adds a \DOMNodeList to the list of nodes.
285 * @param \DOMNodeList $nodes A \DOMNodeList instance
287 public function addNodeList(\DOMNodeList $nodes)
289 foreach ($nodes as $node) {
290 if ($node instanceof \DOMNode) {
291 $this->addNode($node);
297 * Adds an array of \DOMNode instances to the list of nodes.
299 * @param \DOMNode[] $nodes An array of \DOMNode instances
301 public function addNodes(array $nodes)
303 foreach ($nodes as $node) {
309 * Adds a \DOMNode instance to the list of nodes.
311 * @param \DOMNode $node A \DOMNode instance
313 public function addNode(\DOMNode $node)
315 if ($node instanceof \DOMDocument) {
316 $node = $node->documentElement;
319 if (null !== $this->document && $this->document !== $node->ownerDocument) {
320 throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.');
323 if (null === $this->document) {
324 $this->document = $node->ownerDocument;
327 // Don't add duplicate nodes in the Crawler
328 if (in_array($node, $this->nodes, true)) {
332 $this->nodes[] = $node;
336 * Returns a node given its position in the node list.
338 * @param int $position The position
342 public function eq($position)
344 if (isset($this->nodes[$position])) {
345 return $this->createSubCrawler($this->nodes[$position]);
348 return $this->createSubCrawler(null);
352 * Calls an anonymous function on each node of the list.
354 * The anonymous function receives the position and the node wrapped
355 * in a Crawler instance as arguments.
359 * $crawler->filter('h1')->each(function ($node, $i) {
360 * return $node->text();
363 * @param \Closure $closure An anonymous function
365 * @return array An array of values returned by the anonymous function
367 public function each(\Closure $closure)
370 foreach ($this->nodes as $i => $node) {
371 $data[] = $closure($this->createSubCrawler($node), $i);
378 * Slices the list of nodes by $offset and $length.
385 public function slice($offset = 0, $length = null)
387 return $this->createSubCrawler(array_slice($this->nodes, $offset, $length));
391 * Reduces the list of nodes by calling an anonymous function.
393 * To remove a node from the list, the anonymous function must return false.
395 * @param \Closure $closure An anonymous function
399 public function reduce(\Closure $closure)
402 foreach ($this->nodes as $i => $node) {
403 if (false !== $closure($this->createSubCrawler($node), $i)) {
408 return $this->createSubCrawler($nodes);
412 * Returns the first node of the current selection.
416 public function first()
422 * Returns the last node of the current selection.
426 public function last()
428 return $this->eq(count($this->nodes) - 1);
432 * Returns the siblings nodes of the current selection.
436 * @throws \InvalidArgumentException When current node is empty
438 public function siblings()
441 throw new \InvalidArgumentException('The current node list is empty.');
444 return $this->createSubCrawler($this->sibling($this->getNode(0)->parentNode->firstChild));
448 * Returns the next siblings nodes of the current selection.
452 * @throws \InvalidArgumentException When current node is empty
454 public function nextAll()
457 throw new \InvalidArgumentException('The current node list is empty.');
460 return $this->createSubCrawler($this->sibling($this->getNode(0)));
464 * Returns the previous sibling nodes of the current selection.
468 * @throws \InvalidArgumentException
470 public function previousAll()
473 throw new \InvalidArgumentException('The current node list is empty.');
476 return $this->createSubCrawler($this->sibling($this->getNode(0), 'previousSibling'));
480 * Returns the parents nodes of the current selection.
484 * @throws \InvalidArgumentException When current node is empty
486 public function parents()
489 throw new \InvalidArgumentException('The current node list is empty.');
492 $node = $this->getNode(0);
495 while ($node = $node->parentNode) {
496 if (XML_ELEMENT_NODE === $node->nodeType) {
501 return $this->createSubCrawler($nodes);
505 * Returns the children nodes of the current selection.
509 * @throws \InvalidArgumentException When current node is empty
511 public function children()
514 throw new \InvalidArgumentException('The current node list is empty.');
517 $node = $this->getNode(0)->firstChild;
519 return $this->createSubCrawler($node ? $this->sibling($node) : array());
523 * Returns the attribute value of the first node of the list.
525 * @param string $attribute The attribute name
527 * @return string|null The attribute value or null if the attribute does not exist
529 * @throws \InvalidArgumentException When current node is empty
531 public function attr($attribute)
534 throw new \InvalidArgumentException('The current node list is empty.');
537 $node = $this->getNode(0);
539 return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
543 * Returns the node name of the first node of the list.
545 * @return string The node name
547 * @throws \InvalidArgumentException When current node is empty
549 public function nodeName()
552 throw new \InvalidArgumentException('The current node list is empty.');
555 return $this->getNode(0)->nodeName;
559 * Returns the node value of the first node of the list.
561 * @return string The node value
563 * @throws \InvalidArgumentException When current node is empty
565 public function text()
568 throw new \InvalidArgumentException('The current node list is empty.');
571 return $this->getNode(0)->nodeValue;
575 * Returns the first node of the list as HTML.
577 * @return string The node html
579 * @throws \InvalidArgumentException When current node is empty
581 public function html()
584 throw new \InvalidArgumentException('The current node list is empty.');
588 foreach ($this->getNode(0)->childNodes as $child) {
589 $html .= $child->ownerDocument->saveHTML($child);
596 * Evaluates an XPath expression.
598 * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
599 * this method will return either an array of simple types or a new Crawler instance.
601 * @param string $xpath An XPath expression
603 * @return array|Crawler An array of evaluation results or a new Crawler instance
605 public function evaluate($xpath)
607 if (null === $this->document) {
608 throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
612 $domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
614 foreach ($this->nodes as $node) {
615 $data[] = $domxpath->evaluate($xpath, $node);
618 if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
619 return $this->createSubCrawler($data);
626 * Extracts information from the list of nodes.
628 * You can extract attributes or/and the node value (_text).
632 * $crawler->filter('h1 a')->extract(array('_text', 'href'));
634 * @param array $attributes An array of attributes
636 * @return array An array of extracted values
638 public function extract($attributes)
640 $attributes = (array) $attributes;
641 $count = count($attributes);
644 foreach ($this->nodes as $node) {
646 foreach ($attributes as $attribute) {
647 if ('_text' === $attribute) {
648 $elements[] = $node->nodeValue;
650 $elements[] = $node->getAttribute($attribute);
654 $data[] = $count > 1 ? $elements : $elements[0];
661 * Filters the list of nodes with an XPath expression.
663 * The XPath expression is evaluated in the context of the crawler, which
664 * is considered as a fake parent of the elements inside it.
665 * This means that a child selector "div" or "./div" will match only
666 * the div elements of the current crawler, not their children.
668 * @param string $xpath An XPath expression
672 public function filterXPath($xpath)
674 $xpath = $this->relativize($xpath);
676 // If we dropped all expressions in the XPath while preparing it, there would be no match
678 return $this->createSubCrawler(null);
681 return $this->filterRelativeXPath($xpath);
685 * Filters the list of nodes with a CSS selector.
687 * This method only works if you have installed the CssSelector Symfony Component.
689 * @param string $selector A CSS selector
693 * @throws \RuntimeException if the CssSelector Component is not available
695 public function filter($selector)
697 if (!class_exists('Symfony\\Component\\CssSelector\\CssSelectorConverter')) {
698 throw new \RuntimeException('Unable to filter with a CSS selector as the Symfony CssSelector 2.8+ is not installed (you can use filterXPath instead).');
701 $converter = new CssSelectorConverter($this->isHtml);
703 // The CssSelector already prefixes the selector with descendant-or-self::
704 return $this->filterRelativeXPath($converter->toXPath($selector));
708 * Selects links by name or alt value for clickable images.
710 * @param string $value The link text
714 public function selectLink($value)
716 $xpath = sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) ', static::xpathLiteral(' '.$value.' ')).
717 sprintf('or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)]]', static::xpathLiteral(' '.$value.' '));
719 return $this->filterRelativeXPath($xpath);
723 * Selects images by alt value.
725 * @param string $value The image alt
727 * @return self A new instance of Crawler with the filtered list of nodes
729 public function selectImage($value)
731 $xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
733 return $this->filterRelativeXPath($xpath);
737 * Selects a button by name or alt value for images.
739 * @param string $value The button text
743 public function selectButton($value)
745 $translate = 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")';
746 $xpath = sprintf('descendant-or-self::input[((contains(%s, "submit") or contains(%s, "button")) and contains(concat(\' \', normalize-space(string(@value)), \' \'), %s)) ', $translate, $translate, static::xpathLiteral(' '.$value.' ')).
747 sprintf('or (contains(%s, "image") and contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)) or @id=%s or @name=%s] ', $translate, static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value), static::xpathLiteral($value)).
748 sprintf('| descendant-or-self::button[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) or @id=%s or @name=%s]', static::xpathLiteral(' '.$value.' '), static::xpathLiteral($value), static::xpathLiteral($value));
750 return $this->filterRelativeXPath($xpath);
754 * Returns a Link object for the first node in the list.
756 * @param string $method The method for the link (get by default)
758 * @return Link A Link instance
760 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
762 public function link($method = 'get')
765 throw new \InvalidArgumentException('The current node list is empty.');
768 $node = $this->getNode(0);
770 if (!$node instanceof \DOMElement) {
771 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
774 return new Link($node, $this->baseHref, $method);
778 * Returns an array of Link objects for the nodes in the list.
780 * @return Link[] An array of Link instances
782 * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
784 public function links()
787 foreach ($this->nodes as $node) {
788 if (!$node instanceof \DOMElement) {
789 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_class($node)));
792 $links[] = new Link($node, $this->baseHref, 'get');
799 * Returns an Image object for the first node in the list.
801 * @return Image An Image instance
803 * @throws \InvalidArgumentException If the current node list is empty
805 public function image()
808 throw new \InvalidArgumentException('The current node list is empty.');
811 $node = $this->getNode(0);
813 if (!$node instanceof \DOMElement) {
814 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
817 return new Image($node, $this->baseHref);
821 * Returns an array of Image objects for the nodes in the list.
823 * @return Image[] An array of Image instances
825 public function images()
828 foreach ($this as $node) {
829 if (!$node instanceof \DOMElement) {
830 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_class($node)));
833 $images[] = new Image($node, $this->baseHref);
840 * Returns a Form object for the first node in the list.
842 * @param array $values An array of values for the form fields
843 * @param string $method The method for the form
845 * @return Form A Form instance
847 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
849 public function form(array $values = null, $method = null)
852 throw new \InvalidArgumentException('The current node list is empty.');
855 $node = $this->getNode(0);
857 if (!$node instanceof \DOMElement) {
858 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
861 $form = new Form($node, $this->uri, $method, $this->baseHref);
863 if (null !== $values) {
864 $form->setValues($values);
871 * Overloads a default namespace prefix to be used with XPath and CSS expressions.
873 * @param string $prefix
875 public function setDefaultNamespacePrefix($prefix)
877 $this->defaultNamespacePrefix = $prefix;
881 * @param string $prefix
882 * @param string $namespace
884 public function registerNamespace($prefix, $namespace)
886 $this->namespaces[$prefix] = $namespace;
890 * Converts string for XPath expressions.
892 * Escaped characters are: quotes (") and apostrophe (').
896 * echo Crawler::xpathLiteral('foo " bar');
897 * //prints 'foo " bar'
899 * echo Crawler::xpathLiteral("foo ' bar");
900 * //prints "foo ' bar"
902 * echo Crawler::xpathLiteral('a\'b"c');
903 * //prints concat('a', "'", 'b"c')
906 * @param string $s String to be escaped
908 * @return string Converted string
910 public static function xpathLiteral($s)
912 if (false === strpos($s, "'")) {
913 return sprintf("'%s'", $s);
916 if (false === strpos($s, '"')) {
917 return sprintf('"%s"', $s);
923 if (false !== $pos = strpos($string, "'")) {
924 $parts[] = sprintf("'%s'", substr($string, 0, $pos));
926 $string = substr($string, $pos + 1);
928 $parts[] = "'$string'";
933 return sprintf('concat(%s)', implode(', ', $parts));
937 * Filters the list of nodes with an XPath expression.
939 * The XPath expression should already be processed to apply it in the context of each node.
941 * @param string $xpath
945 private function filterRelativeXPath($xpath)
947 $prefixes = $this->findNamespacePrefixes($xpath);
949 $crawler = $this->createSubCrawler(null);
951 foreach ($this->nodes as $node) {
952 $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
953 $crawler->add($domxpath->query($xpath, $node));
960 * Make the XPath relative to the current context.
962 * The returned XPath will match elements matching the XPath inside the current crawler
963 * when running in the context of a node of the crawler.
965 * @param string $xpath
969 private function relativize($xpath)
971 $expressions = array();
973 // An expression which will never match to replace expressions which cannot match in the crawler
974 // We cannot simply drop
975 $nonMatchingExpression = 'a[name() = "b"]';
977 $xpathLen = strlen($xpath);
979 $startPosition = strspn($xpath, " \t\n\r\0\x0B");
981 for ($i = $startPosition; $i <= $xpathLen; ++$i) {
982 $i += strcspn($xpath, '"\'[]|', $i);
984 if ($i < $xpathLen) {
985 switch ($xpath[$i]) {
988 if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
989 return $xpath; // The XPath expression is invalid
1000 if ($openedBrackets) {
1004 if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
1005 // If the union is inside some braces, we need to preserve the opening braces and apply
1006 // the change only inside it.
1007 $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
1008 $parenthesis = substr($xpath, $startPosition, $j);
1009 $startPosition += $j;
1013 $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
1015 if (0 === strpos($expression, 'self::*/')) {
1016 $expression = './'.substr($expression, 8);
1019 // add prefix before absolute element selector
1020 if ('' === $expression) {
1021 $expression = $nonMatchingExpression;
1022 } elseif (0 === strpos($expression, '//')) {
1023 $expression = 'descendant-or-self::'.substr($expression, 2);
1024 } elseif (0 === strpos($expression, './/')) {
1025 $expression = 'descendant-or-self::'.substr($expression, 3);
1026 } elseif (0 === strpos($expression, './')) {
1027 $expression = 'self::'.substr($expression, 2);
1028 } elseif (0 === strpos($expression, 'child::')) {
1029 $expression = 'self::'.substr($expression, 7);
1030 } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
1031 $expression = $nonMatchingExpression;
1032 } elseif (0 === strpos($expression, 'descendant::')) {
1033 $expression = 'descendant-or-self::'.substr($expression, 12);
1034 } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
1035 // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
1036 $expression = $nonMatchingExpression;
1037 } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
1038 $expression = 'self::'.$expression;
1040 $expressions[] = $parenthesis.$expression;
1042 if ($i === $xpathLen) {
1043 return implode(' | ', $expressions);
1046 $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
1047 $startPosition = $i + 1;
1050 return $xpath; // The XPath expression is invalid
1054 * @param int $position
1056 * @return \DOMElement|null
1058 public function getNode($position)
1060 if (isset($this->nodes[$position])) {
1061 return $this->nodes[$position];
1068 public function count()
1070 return count($this->nodes);
1074 * @return \ArrayIterator
1076 public function getIterator()
1078 return new \ArrayIterator($this->nodes);
1082 * @param \DOMElement $node
1083 * @param string $siblingDir
1087 protected function sibling($node, $siblingDir = 'nextSibling')
1092 if ($node !== $this->getNode(0) && $node->nodeType === 1) {
1095 } while ($node = $node->$siblingDir);
1101 * @param \DOMDocument $document
1102 * @param array $prefixes
1106 * @throws \InvalidArgumentException
1108 private function createDOMXPath(\DOMDocument $document, array $prefixes = array())
1110 $domxpath = new \DOMXPath($document);
1112 foreach ($prefixes as $prefix) {
1113 $namespace = $this->discoverNamespace($domxpath, $prefix);
1114 if (null !== $namespace) {
1115 $domxpath->registerNamespace($prefix, $namespace);
1123 * @param \DOMXPath $domxpath
1124 * @param string $prefix
1128 * @throws \InvalidArgumentException
1130 private function discoverNamespace(\DOMXPath $domxpath, $prefix)
1132 if (isset($this->namespaces[$prefix])) {
1133 return $this->namespaces[$prefix];
1136 // ask for one namespace, otherwise we'd get a collection with an item for each node
1137 $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
1139 if ($node = $namespaces->item(0)) {
1140 return $node->nodeValue;
1145 * @param string $xpath
1149 private function findNamespacePrefixes($xpath)
1151 if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
1152 return array_unique($matches['prefix']);
1159 * Creates a crawler for some subnodes.
1161 * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
1165 private function createSubCrawler($nodes)
1167 $crawler = new static($nodes, $this->uri, $this->baseHref);
1168 $crawler->isHtml = $this->isHtml;
1169 $crawler->document = $this->document;
1170 $crawler->namespaces = $this->namespaces;