Example of searching XML file with PHP and XPath

A basic example of searching XML file using PHP XPath queries ...

Home Programming Examples PHP Examples → Example of searching XML file with PHP and XPath
example of searching xml file with php and xpath


Storing data in XML files can be useful in many cases when programming websites with PHP and often, there is a need to also search these files by particular field / column or some combination between them.
In this example, we'll show how we can easily search XML files using XPath queries. Let's say we have some XML with jobs data and we would like to search the job titles by a specific keyword.
Our basic jobs XML files looks like:

   <jobs>
      <job>
         <title>PHP Programmer</title>
         <description>This is a test job for a PHP programmer ... the description goes here</description>
      </job>
      <job>
         <title>JAVA programmer</title>
         <description>Another test job goes here</description>
      </job>
   </jobs>


and let's suppose it's saved in a file jobs.xml, that we want to load from PHP and search by some keyword in the title.
We load the file -


$xml = simplexml_load_file('jobs.xml');


and then we want to show only the jobs having the word JAVA in the title, but using a XPath query


$jobs = $xml->xpath("/jobs/job[contains(title,'JAVA')]");


and finally show the results -


foreach($jobs as $job)
{
   echo $job->title."<br/>";
echo $job->description."<br/>";
}


With XPath we can also make combinations and search by more than one keyword. For example if we want to search by both PHP and Java, we can use -


$jobs = $xml->xpath("/jobs/job[contains(title,'PHP')]|/jobs/job[contains(category,'JAVA')]");



See More PHP ExamplesHire Me For A Project






 
Connect with meLinkedIn ProfileFacebook Profile


2024 © SofiaCoder.com
×

Programming ExamplesPHP ExamplesMySQL ExamplesJavaScript ExamplesHTML ExamplesCSS ExamplesNode.js ExamplesOther Home PageSofia Coder LinkedIn ProfileSofia Coder Facebook Profile