public
Created

Parse XML by Category

  • Download Gist
gistfile1.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
<?php
$jobs = simplexml_load_file('jobfeed.xml');
 
function output_list($jobs = array())
{
$data = array();
 
foreach($jobs->xpath('/jobs/job') as $job_details)
{
$category = $job_details->department;
$title = $job_details->title;
$url = $job_details->url;
 
if(!isset($data[$category]))
{
$data[$category] = array();
}
 
$data[$category][] = '<li>Category: '.$category.'<br>Title: '.$title.'<br>URL: '.$url.'</li>';
}
 
foreach($data as $category => $items)
{
$data[$category] = '<li><ul>'.implode('', $items).'</ul></li>';
}
 
return '<ul>'.implode('', $data).'</ul>';
}
 
echo output_list($jobs);
?>

I only made 2 modifications to the code you wrote:

  • First, the actual XML tag for "category" isn't labeled <category> but <department>, so I changed that on line 10.
  • Second, I added anxpath to the foreach parameters on line 8 to account for extra data inside the real <jobs> tag.

But I don't see how either of those changes would cause errors.

I actually get several EE PHP errors:

line 14:

Illegal offset type in isset or empty

lines 16 & 19:

Illegal offset type

Add right above line 14, var_dump($data);exit();

That will output the $data array and see why there is an error. My guess is the $category variable is NULL or not set correctly and is possible a bad index. You could also do a var_dump($category);exit(); above live 14 to see what the category value is. Ensure that it actually has some value and those errors should do away. You are really close. My logis is 100% correct, it's just conflicts with your data and my code.

var_dump($data); gives me this: array(0) { }

var_dump($category); gives me this: object(SimpleXMLElement)#47 (0) { }

Both would imply that there is no data being returned for the $category variable, which confuses the hell out of me because if I do this:

<ul>
<?php
    $jobs = simplexml_load_file('jobfeed.xml');

    foreach ($jobs->xpath('/jobs/job') as $jobDetails) {
        $category = $jobDetails->department;
        $title = $jobDetails->title;
        $url = $jobDetails->url;

        echo '<li>Category: ',$category,'<br>Title: ',$title,'<br>URL: ',$url,'</li>';
    }
?>
</ul>

The categories are output perfectly fine.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.