regexp for xml - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of regexp for xml.php

  1. <?php
  2.  
  3. $fields = ['ht:news_item_title','ht:news_item_snippet','ht:news_item_url','ht:news_item_source'];
  4.  
  5. $xml = '
  6. <item>
  7.     <title>xxx</title>
  8.     <ht:news_item>
  9.         <ht:news_item_title>Title 1</ht:news_item_title>
  10.         <ht:news_item_snippet>Did you like this tool? You can donate to us. This will help us improve our free web tools.</ht:news_item_snippet>
  11.         <ht:news_item_url>https://google.com</ht:news_item_url>
  12.         <ht:news_item_source>google.com</ht:news_item_source>
  13.     </ht:news_item>
  14.     <ht:news_item>
  15.         <ht:news_item_title>Title 2</ht:news_item_title>
  16.         <ht:news_item_snippet>Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML</ht:news_item_snippet>
  17.         <ht:news_item_url>https://youtube.com</ht:news_item_url>
  18.         <ht:news_item_source>youtube.com</ht:news_item_source>
  19.     </ht:news_item>
  20. </item>
  21. ';
  22.  
  23. preg_match_all('/\<ht\:news_item\>((?!\<\/ht\:news_item\>).)*\<\/ht\:news_item\>/ims', $xml, $items);
  24.  
  25. //print_r($items);
  26.  
  27. $result = [];
  28.  
  29. foreach($items[0] as $key => $item)
  30. {
  31.     //print $item;
  32.     
  33.     $result[$key] = [];
  34.     foreach($fields as $tag_name)
  35.     {
  36.         if(preg_match('/\<'.preg_quote($tag_name).'\>(((?!\<\/'.preg_quote($tag_name).'\>).)*)\<\/'.preg_quote($tag_name).'\>/ims', $item, $matches))
  37.         {
  38.             $result[$key][$tag_name] = $matches[1];
  39.         }
  40.         //print_r($matches);
  41.     }
  42.     //print "\n\n=============\n\n";
  43. }
  44.  
  45. print_r($result);
  46.  
File Description
  • regexp for xml
  • PHP Code
  • 25 Apr-2023
  • 1.47 Kb
You can Share it: