Search code examples
phpxmlforeachpreg-match

How to filter simplexml_load_file foreach loop?


I have the following php code:

<?php
$website_url = 'domain.com/sitemap.xml';
$xml=simplexml_load_file(''. $website_url.'') or die("Error: Cannot create object");
foreach($xml->url as $val)
 {
   echo $val->loc.  '<br>';
 }

It works fine, I get the url's from the xml sitemap file, but I want to filter positive matches (and after that negative matches), for example only lines that contain "apple" and "juice" (and for negative, only lines that don't contain "rss" or "sitemap") . I tried few ways to do it with preg_match but without success, I get blank page results or 500 error. The xml file (a simple sitemap.xml file) I extract and want to filter has around 20000 lines/url's


Solution

  • Try to use http://php.net/strpos for match. you can also check for rss and sitemap:

    foreach($xml->url as $val)
     {
       $url = $val->loc;
        if(strpos($url, 'apple') !== FALSE && strpos($url, 'juice') !== FALSE) {
            echo "keyword found in URL\n";
            break;
        }
        else {
            echo "keyword not found\n";
        }
     }