phparraysxpathnesteddomdocument

Can We use Array Element in DomDocument and nesting xpath?


I am using the following code

    $page_data=array();//$title_links is array having urls
     $nodearr=array();
    foreach ($title_links as $b_url)
    {
        $page_data[]= mycurl($b_url);//my curl function, it is okay

        $dom2 = new DOMDocument();//creating new domdocument object inside a domdocument object
        @$dom2->loadHTML($page_data[]); 
        $xpath_cat = new DOMXPath($dom2);//same as domdocument , nesting xpath
        $nodelist = $xpath_cat->query('//span[@class="zg_hrsr_ladder"]', $dom2);
//echo nodeslist;

foreach ($nodelist as $node) {
   $nodearr[] = $node->textContent;
 }


    }

so the scenerio is ,

  • I am nesting a 'domdocument' inside an other 'DomDocument'
  • using 'foreach loop', i am inserting Array Element in DomDocument
  • aslo, as i am nestind domdocument inside domdocument , so i am declaring new xpath query

  • The Question is ...

  • Doing so is okay? Is it a acceptable Programming technique?
  • Pros and Cons?
  • Any ALternative to it?

    Clarification:

  • $title_links is obtained using curl, it is urls extracted from web page using domdocument and xpath query.
  • so $title_links is at first level of xpath and domdocument, and $nodelist is at the 2nd level of nesting od xpath and dom-document


  • Solution

  • The reason it's failing is this: @$dom2->loadHTML($page_data[]);

    [] can only be used for assignment, not reading. You need to actually have a key you can reference. I would probably do it like this:

    $page_data=array();//$title_links is array having urls
    foreach ($title_links as $key => $b_url)
    {
        $page_data[$key]= mycurl($b_url);//my curl function, it is okay
    
        $dom2 = new DOMDocument();
        $dom2->loadHTML($page_data[$key]); // error suppression is evil!
        $xpath_cat = new DOMXPath($dom2);
    
    }
    

    What's still unclear to me is how exactly there is any nesting going on here; you're not nesting anything, you are just iterating over an array.