Search code examples
phpxmlsimplexml

How to search/filter node content inside of xml file with SimpleXMLElement - php


I need to filter/search all links (png,jpg,mp3) from an XXML file but I got stuck there. I did for example to get all mp3 but I did it knowing that was there, but for example if I put other file where the path is different, then it won't detect it.

    foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a){
    echo '<a href="'.$a->PATH.'">'.$a->PATH.'</a><br>';
    }

Example XML


Solution

  • You could get the extension of each file and compare it to an array of "accepted extensions". Then use, continue to skip to write link:

    $accepted_exts = ['png','jpg','mp3'];
    foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
        $path = $a->PATH;
        $ext = strtolower(substr($path, strrpos($path, '.') + 1));
        if (!in_array($ext, $accepted_exts)) continue ; // continue to next iteration
        echo '<a href="'.$path.'">'.$path.'</a><br>'; // write the link
    }
    

    To get other links:

    $accepted_exts = ['png','jpg','mp3'];
    $links = [] ;
    foreach($xml->HEAD as $items) {
        foreach ($items as $item) {
            $path = (string)$item;
            if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
            $links[] = $path ;
        }
    }
    foreach($xml->BODY->GENERAL->SOUNDS->SOUND as $a) {
        $path = $a->PATH;
        if (!in_array(get_ext($path), $accepted_exts)) continue ; // continue to next iteration
        $links[] = $path ;
    }
    foreach ($links as $path) {
        echo '<a href="'.$path.'">'.$path.'</a><br>'; // write the link
    }
    function get_ext($path) {
        return strtolower(substr($path, strrpos($path, '.') + 1));
    }
    

    Will outputs:

    <a href="http://player.glifing.com/img/Player/blue.png">http://player.glifing.com/img/Player/blue.png</a><br>
    <a href="http://player.glifing.com/img/Player/blue_intro.png">http://player.glifing.com/img/Player/blue_intro.png</a><br>
    <a href="http://player.glifing.com/upload/fondoinstrucciones2.jpg">http://player.glifing.com/upload/fondoinstrucciones2.jpg</a><br>
    <a href="http://player.glifing.com/upload/stopbet2.png">http://player.glifing.com/upload/stopbet2.png</a><br>
    <a href="http://player.glifing.com/upload/goglif2.png">http://player.glifing.com/upload/goglif2.png</a><br>
    <a href="http://player.glifing.com/img/Player/Glif 3 OK.png">http://player.glifing.com/img/Player/Glif 3 OK.png</a><br>
    <a href="http://player.glifing.com/img/Player/BetPensant.png">http://player.glifing.com/img/Player/BetPensant.png</a><br>
    <a href="http://player.glifing.com/audio/Player/si.mp3">http://player.glifing.com/audio/Player/si.mp3</a><br>
    <a href="http://player.glifing.com/audio/Player/no.mp3">http://player.glifing.com/audio/Player/no.mp3</a><br>