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
26 * @var string The default namespace prefix to be used with XPath and CSS expressions
28 private $defaultNamespacePrefix = 'default';
31 * @var array A map of manually registered namespaces
33 private $namespaces = array();
36 * @var string The base href value
41 * @var \DOMDocument|null
48 private $nodes = array();
51 * Whether the Crawler contains HTML or XML content (used when converting CSS to XPath).
55 private $isHtml = true;
58 * @param mixed $node A Node to use as the base for the crawling
59 * @param string $uri The current URI
60 * @param string $baseHref The base href value
62 public function __construct($node = null, $uri = null, $baseHref = null)
65 $this->baseHref = $baseHref ?: $uri;
71 * Returns the current URI.
75 public function getUri()
85 public function getBaseHref()
87 return $this->baseHref;
91 * Removes all the nodes.
93 public function clear()
95 $this->nodes = array();
96 $this->document = null;
100 * Adds a node to the current list of nodes.
102 * This method uses the appropriate specialized add*() method based
103 * on the type of the argument.
105 * @param \DOMNodeList|\DOMNode|array|string|null $node A node
107 * @throws \InvalidArgumentException when node is not the expected type
109 public function add($node)
111 if ($node instanceof \DOMNodeList) {
112 $this->addNodeList($node);
113 } elseif ($node instanceof \DOMNode) {
114 $this->addNode($node);
115 } elseif (is_array($node)) {
116 $this->addNodes($node);
117 } elseif (is_string($node)) {
118 $this->addContent($node);
119 } elseif (null !== $node) {
120 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)));
125 * Adds HTML/XML content.
127 * If the charset is not set via the content type, it is assumed to be UTF-8,
128 * or ISO-8859-1 as a fallback, which is the default charset defined by the
129 * HTTP 1.1 specification.
131 * @param string $content A string to parse as HTML/XML
132 * @param null|string $type The content type of the string
134 public function addContent($content, $type = null)
137 $type = 0 === strpos($content, '<?xml') ? 'application/xml' : 'text/html';
140 // DOM only for HTML/XML content
141 if (!preg_match('/(x|ht)ml/i', $type, $xmlMatches)) {
146 if (false !== $pos = stripos($type, 'charset=')) {
147 $charset = substr($type, $pos + 8);
148 if (false !== $pos = strpos($charset, ';')) {
149 $charset = substr($charset, 0, $pos);
153 // http://www.w3.org/TR/encoding/#encodings
154 // http://www.w3.org/TR/REC-xml/#NT-EncName
155 if (null === $charset &&
156 preg_match('/\<meta[^\>]+charset *= *["\']?([a-zA-Z\-0-9_:.]+)/i', $content, $matches)) {
157 $charset = $matches[1];
160 if (null === $charset) {
161 $charset = preg_match('//u', $content) ? 'UTF-8' : 'ISO-8859-1';
164 if ('x' === $xmlMatches[1]) {
165 $this->addXmlContent($content, $charset);
167 $this->addHtmlContent($content, $charset);
172 * Adds an HTML content to the list of nodes.
174 * The libxml errors are disabled when the content is parsed.
176 * If you want to get parsing errors, be sure to enable
177 * internal errors via libxml_use_internal_errors(true)
178 * and then, get the errors via libxml_get_errors(). Be
179 * sure to clear errors with libxml_clear_errors() afterward.
181 * @param string $content The HTML content
182 * @param string $charset The charset
184 public function addHtmlContent($content, $charset = 'UTF-8')
186 $internalErrors = libxml_use_internal_errors(true);
187 $disableEntities = libxml_disable_entity_loader(true);
189 $dom = new \DOMDocument('1.0', $charset);
190 $dom->validateOnParse = true;
192 set_error_handler(function () { throw new \Exception(); });
195 // Convert charset to HTML-entities to work around bugs in DOMDocument::loadHTML()
196 $content = mb_convert_encoding($content, 'HTML-ENTITIES', $charset);
197 } catch (\Exception $e) {
200 restore_error_handler();
202 if ('' !== trim($content)) {
203 @$dom->loadHTML($content);
206 libxml_use_internal_errors($internalErrors);
207 libxml_disable_entity_loader($disableEntities);
209 $this->addDocument($dom);
211 $base = $this->filterRelativeXPath('descendant-or-self::base')->extract(array('href'));
213 $baseHref = current($base);
214 if (count($base) && !empty($baseHref)) {
215 if ($this->baseHref) {
216 $linkNode = $dom->createElement('a');
217 $linkNode->setAttribute('href', $baseHref);
218 $link = new Link($linkNode, $this->baseHref);
219 $this->baseHref = $link->getUri();
221 $this->baseHref = $baseHref;
227 * Adds an XML content to the list of nodes.
229 * The libxml errors are disabled when the content is parsed.
231 * If you want to get parsing errors, be sure to enable
232 * internal errors via libxml_use_internal_errors(true)
233 * and then, get the errors via libxml_get_errors(). Be
234 * sure to clear errors with libxml_clear_errors() afterward.
236 * @param string $content The XML content
237 * @param string $charset The charset
238 * @param int $options Bitwise OR of the libxml option constants
239 * LIBXML_PARSEHUGE is dangerous, see
240 * http://symfony.com/blog/security-release-symfony-2-0-17-released
242 public function addXmlContent($content, $charset = 'UTF-8', $options = LIBXML_NONET)
244 // remove the default namespace if it's the only namespace to make XPath expressions simpler
245 if (!preg_match('/xmlns:/', $content)) {
246 $content = str_replace('xmlns', 'ns', $content);
249 $internalErrors = libxml_use_internal_errors(true);
250 $disableEntities = libxml_disable_entity_loader(true);
252 $dom = new \DOMDocument('1.0', $charset);
253 $dom->validateOnParse = true;
255 if ('' !== trim($content)) {
256 @$dom->loadXML($content, $options);
259 libxml_use_internal_errors($internalErrors);
260 libxml_disable_entity_loader($disableEntities);
262 $this->addDocument($dom);
264 $this->isHtml = false;
268 * Adds a \DOMDocument to the list of nodes.
270 * @param \DOMDocument $dom A \DOMDocument instance
272 public function addDocument(\DOMDocument $dom)
274 if ($dom->documentElement) {
275 $this->addNode($dom->documentElement);
280 * Adds a \DOMNodeList to the list of nodes.
282 * @param \DOMNodeList $nodes A \DOMNodeList instance
284 public function addNodeList(\DOMNodeList $nodes)
286 foreach ($nodes as $node) {
287 if ($node instanceof \DOMNode) {
288 $this->addNode($node);
294 * Adds an array of \DOMNode instances to the list of nodes.
296 * @param \DOMNode[] $nodes An array of \DOMNode instances
298 public function addNodes(array $nodes)
300 foreach ($nodes as $node) {
306 * Adds a \DOMNode instance to the list of nodes.
308 * @param \DOMNode $node A \DOMNode instance
310 public function addNode(\DOMNode $node)
312 if ($node instanceof \DOMDocument) {
313 $node = $node->documentElement;
316 if (null !== $this->document && $this->document !== $node->ownerDocument) {
317 throw new \InvalidArgumentException('Attaching DOM nodes from multiple documents in the same crawler is forbidden.');
320 if (null === $this->document) {
321 $this->document = $node->ownerDocument;
324 // Don't add duplicate nodes in the Crawler
325 if (in_array($node, $this->nodes, true)) {
329 $this->nodes[] = $node;
333 * Returns a node given its position in the node list.
335 * @param int $position The position
339 public function eq($position)
341 if (isset($this->nodes[$position])) {
342 return $this->createSubCrawler($this->nodes[$position]);
345 return $this->createSubCrawler(null);
349 * Calls an anonymous function on each node of the list.
351 * The anonymous function receives the position and the node wrapped
352 * in a Crawler instance as arguments.
356 * $crawler->filter('h1')->each(function ($node, $i) {
357 * return $node->text();
360 * @param \Closure $closure An anonymous function
362 * @return array An array of values returned by the anonymous function
364 public function each(\Closure $closure)
367 foreach ($this->nodes as $i => $node) {
368 $data[] = $closure($this->createSubCrawler($node), $i);
375 * Slices the list of nodes by $offset and $length.
382 public function slice($offset = 0, $length = null)
384 return $this->createSubCrawler(array_slice($this->nodes, $offset, $length));
388 * Reduces the list of nodes by calling an anonymous function.
390 * To remove a node from the list, the anonymous function must return false.
392 * @param \Closure $closure An anonymous function
396 public function reduce(\Closure $closure)
399 foreach ($this->nodes as $i => $node) {
400 if (false !== $closure($this->createSubCrawler($node), $i)) {
405 return $this->createSubCrawler($nodes);
409 * Returns the first node of the current selection.
413 public function first()
419 * Returns the last node of the current selection.
423 public function last()
425 return $this->eq(count($this->nodes) - 1);
429 * Returns the siblings nodes of the current selection.
433 * @throws \InvalidArgumentException When current node is empty
435 public function siblings()
438 throw new \InvalidArgumentException('The current node list is empty.');
441 return $this->createSubCrawler($this->sibling($this->getNode(0)->parentNode->firstChild));
445 * Returns the next siblings nodes of the current selection.
449 * @throws \InvalidArgumentException When current node is empty
451 public function nextAll()
454 throw new \InvalidArgumentException('The current node list is empty.');
457 return $this->createSubCrawler($this->sibling($this->getNode(0)));
461 * Returns the previous sibling nodes of the current selection.
465 * @throws \InvalidArgumentException
467 public function previousAll()
470 throw new \InvalidArgumentException('The current node list is empty.');
473 return $this->createSubCrawler($this->sibling($this->getNode(0), 'previousSibling'));
477 * Returns the parents nodes of the current selection.
481 * @throws \InvalidArgumentException When current node is empty
483 public function parents()
486 throw new \InvalidArgumentException('The current node list is empty.');
489 $node = $this->getNode(0);
492 while ($node = $node->parentNode) {
493 if (XML_ELEMENT_NODE === $node->nodeType) {
498 return $this->createSubCrawler($nodes);
502 * Returns the children nodes of the current selection.
506 * @throws \InvalidArgumentException When current node is empty
508 public function children()
511 throw new \InvalidArgumentException('The current node list is empty.');
514 $node = $this->getNode(0)->firstChild;
516 return $this->createSubCrawler($node ? $this->sibling($node) : array());
520 * Returns the attribute value of the first node of the list.
522 * @param string $attribute The attribute name
524 * @return string|null The attribute value or null if the attribute does not exist
526 * @throws \InvalidArgumentException When current node is empty
528 public function attr($attribute)
531 throw new \InvalidArgumentException('The current node list is empty.');
534 $node = $this->getNode(0);
536 return $node->hasAttribute($attribute) ? $node->getAttribute($attribute) : null;
540 * Returns the node name of the first node of the list.
542 * @return string The node name
544 * @throws \InvalidArgumentException When current node is empty
546 public function nodeName()
549 throw new \InvalidArgumentException('The current node list is empty.');
552 return $this->getNode(0)->nodeName;
556 * Returns the node value of the first node of the list.
558 * @return string The node value
560 * @throws \InvalidArgumentException When current node is empty
562 public function text()
565 throw new \InvalidArgumentException('The current node list is empty.');
568 return $this->getNode(0)->nodeValue;
572 * Returns the first node of the list as HTML.
574 * @return string The node html
576 * @throws \InvalidArgumentException When current node is empty
578 public function html()
581 throw new \InvalidArgumentException('The current node list is empty.');
585 foreach ($this->getNode(0)->childNodes as $child) {
586 $html .= $child->ownerDocument->saveHTML($child);
593 * Evaluates an XPath expression.
595 * Since an XPath expression might evaluate to either a simple type or a \DOMNodeList,
596 * this method will return either an array of simple types or a new Crawler instance.
598 * @param string $xpath An XPath expression
600 * @return array|Crawler An array of evaluation results or a new Crawler instance
602 public function evaluate($xpath)
604 if (null === $this->document) {
605 throw new \LogicException('Cannot evaluate the expression on an uninitialized crawler.');
609 $domxpath = $this->createDOMXPath($this->document, $this->findNamespacePrefixes($xpath));
611 foreach ($this->nodes as $node) {
612 $data[] = $domxpath->evaluate($xpath, $node);
615 if (isset($data[0]) && $data[0] instanceof \DOMNodeList) {
616 return $this->createSubCrawler($data);
623 * Extracts information from the list of nodes.
625 * You can extract attributes or/and the node value (_text).
629 * $crawler->filter('h1 a')->extract(array('_text', 'href'));
631 * @param array $attributes An array of attributes
633 * @return array An array of extracted values
635 public function extract($attributes)
637 $attributes = (array) $attributes;
638 $count = count($attributes);
641 foreach ($this->nodes as $node) {
643 foreach ($attributes as $attribute) {
644 if ('_text' === $attribute) {
645 $elements[] = $node->nodeValue;
647 $elements[] = $node->getAttribute($attribute);
651 $data[] = $count > 1 ? $elements : $elements[0];
658 * Filters the list of nodes with an XPath expression.
660 * The XPath expression is evaluated in the context of the crawler, which
661 * is considered as a fake parent of the elements inside it.
662 * This means that a child selector "div" or "./div" will match only
663 * the div elements of the current crawler, not their children.
665 * @param string $xpath An XPath expression
669 public function filterXPath($xpath)
671 $xpath = $this->relativize($xpath);
673 // If we dropped all expressions in the XPath while preparing it, there would be no match
675 return $this->createSubCrawler(null);
678 return $this->filterRelativeXPath($xpath);
682 * Filters the list of nodes with a CSS selector.
684 * This method only works if you have installed the CssSelector Symfony Component.
686 * @param string $selector A CSS selector
690 * @throws \RuntimeException if the CssSelector Component is not available
692 public function filter($selector)
694 if (!class_exists(CssSelectorConverter::class)) {
695 throw new \RuntimeException('To filter with a CSS selector, install the CssSelector component ("composer require symfony/css-selector"). Or use filterXpath instead.');
698 $converter = new CssSelectorConverter($this->isHtml);
700 // The CssSelector already prefixes the selector with descendant-or-self::
701 return $this->filterRelativeXPath($converter->toXPath($selector));
705 * Selects links by name or alt value for clickable images.
707 * @param string $value The link text
711 public function selectLink($value)
713 $xpath = sprintf('descendant-or-self::a[contains(concat(\' \', normalize-space(string(.)), \' \'), %s) ', static::xpathLiteral(' '.$value.' ')).
714 sprintf('or ./img[contains(concat(\' \', normalize-space(string(@alt)), \' \'), %s)]]', static::xpathLiteral(' '.$value.' '));
716 return $this->filterRelativeXPath($xpath);
720 * Selects images by alt value.
722 * @param string $value The image alt
724 * @return self A new instance of Crawler with the filtered list of nodes
726 public function selectImage($value)
728 $xpath = sprintf('descendant-or-self::img[contains(normalize-space(string(@alt)), %s)]', static::xpathLiteral($value));
730 return $this->filterRelativeXPath($xpath);
734 * Selects a button by name or alt value for images.
736 * @param string $value The button text
740 public function selectButton($value)
742 $translate = 'translate(@type, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", "abcdefghijklmnopqrstuvwxyz")';
743 $xpath = sprintf('descendant-or-self::input[((contains(%s, "submit") or contains(%1$s, "button")) and contains(concat(\' \', normalize-space(string(@value)), \' \'), %s)) ', $translate, static::xpathLiteral(' '.$value.' ')).
744 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)).
745 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));
747 return $this->filterRelativeXPath($xpath);
751 * Returns a Link object for the first node in the list.
753 * @param string $method The method for the link (get by default)
755 * @return Link A Link instance
757 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
759 public function link($method = 'get')
762 throw new \InvalidArgumentException('The current node list is empty.');
765 $node = $this->getNode(0);
767 if (!$node instanceof \DOMElement) {
768 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
771 return new Link($node, $this->baseHref, $method);
775 * Returns an array of Link objects for the nodes in the list.
777 * @return Link[] An array of Link instances
779 * @throws \InvalidArgumentException If the current node list contains non-DOMElement instances
781 public function links()
784 foreach ($this->nodes as $node) {
785 if (!$node instanceof \DOMElement) {
786 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_class($node)));
789 $links[] = new Link($node, $this->baseHref, 'get');
796 * Returns an Image object for the first node in the list.
798 * @return Image An Image instance
800 * @throws \InvalidArgumentException If the current node list is empty
802 public function image()
805 throw new \InvalidArgumentException('The current node list is empty.');
808 $node = $this->getNode(0);
810 if (!$node instanceof \DOMElement) {
811 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
814 return new Image($node, $this->baseHref);
818 * Returns an array of Image objects for the nodes in the list.
820 * @return Image[] An array of Image instances
822 public function images()
825 foreach ($this as $node) {
826 if (!$node instanceof \DOMElement) {
827 throw new \InvalidArgumentException(sprintf('The current node list should contain only DOMElement instances, "%s" found.', get_class($node)));
830 $images[] = new Image($node, $this->baseHref);
837 * Returns a Form object for the first node in the list.
839 * @param array $values An array of values for the form fields
840 * @param string $method The method for the form
842 * @return Form A Form instance
844 * @throws \InvalidArgumentException If the current node list is empty or the selected node is not instance of DOMElement
846 public function form(array $values = null, $method = null)
849 throw new \InvalidArgumentException('The current node list is empty.');
852 $node = $this->getNode(0);
854 if (!$node instanceof \DOMElement) {
855 throw new \InvalidArgumentException(sprintf('The selected node should be instance of DOMElement, got "%s".', get_class($node)));
858 $form = new Form($node, $this->uri, $method, $this->baseHref);
860 if (null !== $values) {
861 $form->setValues($values);
868 * Overloads a default namespace prefix to be used with XPath and CSS expressions.
870 * @param string $prefix
872 public function setDefaultNamespacePrefix($prefix)
874 $this->defaultNamespacePrefix = $prefix;
878 * @param string $prefix
879 * @param string $namespace
881 public function registerNamespace($prefix, $namespace)
883 $this->namespaces[$prefix] = $namespace;
887 * Converts string for XPath expressions.
889 * Escaped characters are: quotes (") and apostrophe (').
893 * echo Crawler::xpathLiteral('foo " bar');
894 * //prints 'foo " bar'
896 * echo Crawler::xpathLiteral("foo ' bar");
897 * //prints "foo ' bar"
899 * echo Crawler::xpathLiteral('a\'b"c');
900 * //prints concat('a', "'", 'b"c')
903 * @param string $s String to be escaped
905 * @return string Converted string
907 public static function xpathLiteral($s)
909 if (false === strpos($s, "'")) {
910 return sprintf("'%s'", $s);
913 if (false === strpos($s, '"')) {
914 return sprintf('"%s"', $s);
920 if (false !== $pos = strpos($string, "'")) {
921 $parts[] = sprintf("'%s'", substr($string, 0, $pos));
923 $string = substr($string, $pos + 1);
925 $parts[] = "'$string'";
930 return sprintf('concat(%s)', implode(', ', $parts));
934 * Filters the list of nodes with an XPath expression.
936 * The XPath expression should already be processed to apply it in the context of each node.
938 * @param string $xpath
942 private function filterRelativeXPath($xpath)
944 $prefixes = $this->findNamespacePrefixes($xpath);
946 $crawler = $this->createSubCrawler(null);
948 foreach ($this->nodes as $node) {
949 $domxpath = $this->createDOMXPath($node->ownerDocument, $prefixes);
950 $crawler->add($domxpath->query($xpath, $node));
957 * Make the XPath relative to the current context.
959 * The returned XPath will match elements matching the XPath inside the current crawler
960 * when running in the context of a node of the crawler.
962 * @param string $xpath
966 private function relativize($xpath)
968 $expressions = array();
970 // An expression which will never match to replace expressions which cannot match in the crawler
971 // We cannot simply drop
972 $nonMatchingExpression = 'a[name() = "b"]';
974 $xpathLen = strlen($xpath);
976 $startPosition = strspn($xpath, " \t\n\r\0\x0B");
978 for ($i = $startPosition; $i <= $xpathLen; ++$i) {
979 $i += strcspn($xpath, '"\'[]|', $i);
981 if ($i < $xpathLen) {
982 switch ($xpath[$i]) {
985 if (false === $i = strpos($xpath, $xpath[$i], $i + 1)) {
986 return $xpath; // The XPath expression is invalid
997 if ($openedBrackets) {
1001 if ($startPosition < $xpathLen && '(' === $xpath[$startPosition]) {
1002 // If the union is inside some braces, we need to preserve the opening braces and apply
1003 // the change only inside it.
1004 $j = 1 + strspn($xpath, "( \t\n\r\0\x0B", $startPosition + 1);
1005 $parenthesis = substr($xpath, $startPosition, $j);
1006 $startPosition += $j;
1010 $expression = rtrim(substr($xpath, $startPosition, $i - $startPosition));
1012 if (0 === strpos($expression, 'self::*/')) {
1013 $expression = './'.substr($expression, 8);
1016 // add prefix before absolute element selector
1017 if ('' === $expression) {
1018 $expression = $nonMatchingExpression;
1019 } elseif (0 === strpos($expression, '//')) {
1020 $expression = 'descendant-or-self::'.substr($expression, 2);
1021 } elseif (0 === strpos($expression, './/')) {
1022 $expression = 'descendant-or-self::'.substr($expression, 3);
1023 } elseif (0 === strpos($expression, './')) {
1024 $expression = 'self::'.substr($expression, 2);
1025 } elseif (0 === strpos($expression, 'child::')) {
1026 $expression = 'self::'.substr($expression, 7);
1027 } elseif ('/' === $expression[0] || '.' === $expression[0] || 0 === strpos($expression, 'self::')) {
1028 $expression = $nonMatchingExpression;
1029 } elseif (0 === strpos($expression, 'descendant::')) {
1030 $expression = 'descendant-or-self::'.substr($expression, 12);
1031 } elseif (preg_match('/^(ancestor|ancestor-or-self|attribute|following|following-sibling|namespace|parent|preceding|preceding-sibling)::/', $expression)) {
1032 // the fake root has no parent, preceding or following nodes and also no attributes (even no namespace attributes)
1033 $expression = $nonMatchingExpression;
1034 } elseif (0 !== strpos($expression, 'descendant-or-self::')) {
1035 $expression = 'self::'.$expression;
1037 $expressions[] = $parenthesis.$expression;
1039 if ($i === $xpathLen) {
1040 return implode(' | ', $expressions);
1043 $i += strspn($xpath, " \t\n\r\0\x0B", $i + 1);
1044 $startPosition = $i + 1;
1047 return $xpath; // The XPath expression is invalid
1051 * @param int $position
1053 * @return \DOMElement|null
1055 public function getNode($position)
1057 if (isset($this->nodes[$position])) {
1058 return $this->nodes[$position];
1065 public function count()
1067 return count($this->nodes);
1071 * @return \ArrayIterator|\DOMElement[]
1073 public function getIterator()
1075 return new \ArrayIterator($this->nodes);
1079 * @param \DOMElement $node
1080 * @param string $siblingDir
1084 protected function sibling($node, $siblingDir = 'nextSibling')
1089 if ($node !== $this->getNode(0) && 1 === $node->nodeType) {
1092 } while ($node = $node->$siblingDir);
1098 * @param \DOMDocument $document
1099 * @param array $prefixes
1103 * @throws \InvalidArgumentException
1105 private function createDOMXPath(\DOMDocument $document, array $prefixes = array())
1107 $domxpath = new \DOMXPath($document);
1109 foreach ($prefixes as $prefix) {
1110 $namespace = $this->discoverNamespace($domxpath, $prefix);
1111 if (null !== $namespace) {
1112 $domxpath->registerNamespace($prefix, $namespace);
1120 * @param \DOMXPath $domxpath
1121 * @param string $prefix
1125 * @throws \InvalidArgumentException
1127 private function discoverNamespace(\DOMXPath $domxpath, $prefix)
1129 if (isset($this->namespaces[$prefix])) {
1130 return $this->namespaces[$prefix];
1133 // ask for one namespace, otherwise we'd get a collection with an item for each node
1134 $namespaces = $domxpath->query(sprintf('(//namespace::*[name()="%s"])[last()]', $this->defaultNamespacePrefix === $prefix ? '' : $prefix));
1136 if ($node = $namespaces->item(0)) {
1137 return $node->nodeValue;
1142 * @param string $xpath
1146 private function findNamespacePrefixes($xpath)
1148 if (preg_match_all('/(?P<prefix>[a-z_][a-z_0-9\-\.]*+):[^"\/:]/i', $xpath, $matches)) {
1149 return array_unique($matches['prefix']);
1156 * Creates a crawler for some subnodes.
1158 * @param \DOMElement|\DOMElement[]|\DOMNodeList|null $nodes
1162 private function createSubCrawler($nodes)
1164 $crawler = new static($nodes, $this->uri, $this->baseHref);
1165 $crawler->isHtml = $this->isHtml;
1166 $crawler->document = $this->document;
1167 $crawler->namespaces = $this->namespaces;