2017-02-25 5 views
1

Ich arbeite an einer Erweiterung der DOMXPath-Bibliothek. Ich möchte wie dieser Methode ist, wie dieseSo erweitern Sie DOMNodeList in PHP

public function extract($attributes) 
{ 
    $attributes = (array) $attributes; 
    $data = array(); 

    foreach ("Allnodes" as $node) { // How can I get all nodes from the query? 
     $elements = array(); 
     foreach ($attributes as $attribute) { 
       $data[] = $node->getAttribute($attribute); 
     } 
    } 
    return $data; 
} 

$aHref = (new DOMXPath($domDoc))->query('descendant-or-self::base') 
           ->extract(array('href')); 

Meine Extrakt Informationen aus der Liste der Knoten extrahiert Wie würde ich DOMNodeList/DOMXPath erweitern, das zu tun?

+0

Bitte benutzen Sie Versuche, über die Knoten zu iterieren? So etwas wie - für ($ i = 0; $ i < $nodes-> childNodes-> length; $ i ++) – Ashish

+0

Hmmm, wie bekomme ich alle Listenknoten '$ nodes-> childNodes-> length' – LeMoussel

Antwort

1

Was Sie tun können, ist die folgende:

// create a wrapper class for DOMNodeList 
class MyNodeList 
{ 
    private $nodeList; 

    public function __construct(DOMNodeList $nodeList) { 
    $this->nodeList = $nodeList; 
    } 

    // beware that this function returns a flat array of 
    // all desired attributes of all nodes in the list 
    // how I think it was originally intended 
    // But, since it won't be some kind of nested list, 
    // I'm not sure how useful this actually is 
    public function extract($attributes) { 
    $attributes = (array) $attributes; 
    $data = array(); 

    foreach($this->nodeList as $node) { 
     foreach($attributes as $attribute) { 
     $data[] = $node->getAttribute($attribute); 
     } 
    } 

    return $data; 
    } 
} 

// extend DOMXPath 
class MyXPath 
    extends DOMXPath 
{ 
    // override the original query() to wrap the result 
    // in your MyNodeList, if the original result is a DOMNodeList 
    public function query($expression, DOMNode $contextNode = null, $registerNodeNS = true) { 
    $result = $this->xpath()->query($expression, $contextNode, $registerNodeNS); 
    if($result instanceof DOMNodeList) { 
     $result = new MyNodeList($result); 
    } 

    return $result; 
    } 
} 

Anwendungsbeispiel wäre dann fast identisch mit Ihrer Original-Code, außer Sie MyXPath statt DOMXPath instanziiert würde:

$aHref = (new MyXPath($domDoc))->query('descendant-or-self::base') 
            ->extract(array('href'));