Combining two Xpaths into one loop?

前端 未结 3 483
故里飘歌
故里飘歌 2021-01-22 17:03

I\'m using xpath to grab information from a document, the only issue is I havn\'t been able to combine them into 1 for loop so the information displays correctly on the page. My

3条回答
  •  抹茶落季
    2021-01-22 17:24

    This depends a bit on what you're trying to achieve. You can combine two xpath expressions by using the Union operator (pipe |):

    $unitName = $xpath->evaluate("
    (
        //ILS_Unit[@FloorplanID='550584']/Unit/MITS:MarketingName
        |//ILS_Unit[@FloorplanID='550584']/Unit/MITS:Information/MITS:MarketRent
    )
    ");
    

    Which then would return all evaluated nodes in document order:

    1265.0000 C-304 1265.0000 C-308 1255.0000 C-204 1255.0000 C-208 1230.0000 C-102 1230.0000 C-103

    Which is probably not what you're looking for. Instead you want to either evaluate over both results the same time, which can be achieved with a MultipleIterator:

    $unitName  = $xpath->evaluate("//ILS_Unit[@FloorplanID='550584']/Unit/MITS:MarketingName");
    $unitPrice = $xpath->evaluate("//ILS_Unit[@FloorplanID='550584']/Unit/MITS:Information/MITS:MarketRent");
    
    $it = new MultipleIterator();
    $it->attachIterator(new IteratorIterator($unitName));
    $it->attachIterator(new IteratorIterator($unitPrice));
    
    foreach($it as $value) {
        list($name, $price) = $value;
        echo " * ", $name->nodeValue, " ", $price->nodeValue, "\n";
    }
    

    Output:

     * C-304 1265.0000
     * C-308 1265.0000
     * C-204 1255.0000
     * C-208 1255.0000
     * C-102 1230.0000
     * C-103 1230.0000
    

    This is probably more what you're looking for. Also for what you do, SimpleXMLElement might be more easy to use because it already allows to output nodes in string context.

    Additionally there is another concept that directly maps shallow objects to an underlying XML document and it has been outlined here:

    • Extracting data from HTML using PHP and xPath

    It is quite an interesting concept. IIRC I wrote something similar like applying one xpath query onto all nodes of another one, but I don't find it right now.

提交回复
热议问题