2017-02-25 7 views
1

私はDOMXPathライブラリの拡張機能を開発中です。 私は私の抽出方法は、どのように私はそれをするのDOMNodeList/DOMXPathを使うことの最大を延長するこのPHPでDOMNodeListを拡張する方法

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')); 

のようなノードのリストから情報を抽出したいですか

+0

はあなたをしましたノードを反復処理してみてください。 何かのようなもの - for($ i = 0; $ i < $nodes-> childNodes-> length; $ i ++) – Ashish

+0

Hmmm、どのようにしてすべてのリストノード '$ nodes-> childNodes-> length'を得ることができますか? – LeMoussel

答えて

1

あなたは何ができるか、以下の通りです:あなたの代わりにDOMXPathMyXPathをインスタンス化したい除い

// 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; 
    } 
} 

使用例は、その後、ほぼ、元のコードと同じになります:

$aHref = (new MyXPath($domDoc))->query('descendant-or-self::base') 
            ->extract(array('href')); 
関連する問題