Search code examples
phpxmlfeed

PHP/XML feed reader where to start?


I have a question regarding XML feeds.

There is a website whitch provides data and they give me 2 links for 2 files

  • file 1 : Cars_docu.atom
  • file 2 : Cars.atom

date on file 1 is like this

 <entry>
<author>
  <name />
</author>
<f:name>Name</f:name>
<f:description>Product name</f:description>

and the second file is like this

 <entry>
<title>Volvo</title>
<link rel="alternate" href="#1" />
<author>
  <name />
</author>
<id>237370</id>
<updated>2015-08-17T11:44:32Z</updated>
<f:name>Volvo Lamp</f:name>

So as I understand the first file includes name of the filds and the second one includes the data

My question is what is the method of pulling this imformation from both files using a PHP file and gather them into one page ?

and inside the second document there is a 10000 product so how i pull one pacific product only?

I need methods if you have code I will be glad or just tell me where to start

regads


Solution

  • Take a look at the SimpleXML Class: http://php.net/manual/en/class.simplexmlelement.php

    The approach to take is to use file_get_contents to pull the data from the XML pages and then use SimpleXML to parse it into an array.

    For example:

    <?php
    
    $url = "somewebsite.com/Cars.atom";
    
    $file = file_get_contents($url);
    
    $carsArray = new SimpleXMLElement($file);
    
    foreach ($carsArray->entry as $car) {
    
       echo $car->title; // Would display "Volvo"
    
    }
    
    ?>
    

    When I'm first investigating the structure of an XML document that has been parsed into an array I find it useful to use the print_r() function.

    From the above, the next simple step is to load both XML doc's and work you way through to build the data you want to display.

    Edit if you want to match a specific item Assuming you are wanting to match the car title to Volvo, this is how you could do it.

    <?php
    
    $url = "somewebsite.com/Cars.atom";
    
    $file = file_get_contents($url);
    
    $carsArray = new SimpleXMLElement($file);
    
    // Need to use an array key to get the element, alternatively can loop through each value
    if($carsArray->entry[0]->title == "Volvo") {
        echo "Car is a Volvo!";
    }
    
    ?>