PHP and XML. Looping through an XML file with PHP

前端 未结 3 449
情书的邮戳
情书的邮戳 2021-01-14 17:07

I am knee deep in foreach purgatory right now trying to come up with a way to traverse this XML file (actual XML text below) with PHP(following the XML file content.) What I

相关标签:
3条回答
  • 2021-01-14 18:02

    Recursion could be beneficial to you here.

    <?php
    
    function display_entities( $xml )
    {
        foreach($xml->children() as $child) {
            foreach($child->attributes() as $attr => $attrVal) {
                print $child;
                if($attrVal == "yes") {
                  display_entities( $child->children() );
                }
            }
        }
    }
    
    $xmlref = simplexml_load_file("gallerylisting.xml");
    
    display_entities($xmlref->children());
    
    0 讨论(0)
  • 2021-01-14 18:02

    Use XPath:

    If subfolder=no is unreliable in leaves (i.e. 'no' might not always be set):

    foreach($xmlref->xpath('//folder[not(@subfolder) or @subfolder!="yes"]') as $node){
    

    If it is:

    foreach($xmlref->xpath('//folder[@subfolder="no"]') as $node){
    

    Or even if you want to check for folders without folder children altogether, disregarding the attribute:

    foreach($xmlref->xpath('//folder[not(folder)]') as $node){
    
    0 讨论(0)
  • 2021-01-14 18:03

    You could try use xpath instead of your nested loops method..

    Running the query

    gallerylisting//folder[@subfolder="yes"]/text() 
    

    on your xml doc given above using this xpath tester gives the results Events and Beach_Clean_2010, which is what I think you want. The query will find all folder elements under the root node gallerylisting, and if they have a subfolder attribute equal to "yes", the text in the node will be returned.

    So, in PHP, we have

    <?php
        $xmldoc = new DOMDocument();
        $xmldoc->load('gallerylisting.xml');
    
        $xpathvar = new Domxpath($xmldoc);
    
        $queryResult = $xpathvar->query('gallerylisting//folder[@subfolder="yes"]/text()');
        foreach($queryResult as $result){
                echo $result->textContent;
        }
    ?>
    

    Im not a PHP guy, so I am trusting the code in this StackOverflow question works. One thing to be aware of is that using the //name in xpath means find all nodes descended from the current position that match the name. This can be very slow on large documents.

    It seems there is multiple ways to process xpath with PHP. An example from this page does the query like so:

       $result = $xml->xpath("gallerylisting//folder[@subfolder="yes"]/text()");
    
       print_r($result);
    ?> 
    
    0 讨论(0)
提交回复
热议问题