sorting XML with PHP, returning JSON

mobimano

New Member
I'm wondering if there's a better way I could be doing this. I'm reading XML from a feed, sorting the nodes (because whoever created it can't...), and then returning as JSON (because this is an AJAX call and parsing XML in JavaScript sucks).I've been using Nev Stokes' awesome xsort function found at How to sort a multi-dimensional XML file?, but I ran into an issue when json encoding the the sorted XML (wasn't coming back to JavaScript as JSON) which I think is from drilling down to 'Job' in xpath. The way I got around it feels pretty dirty, so I'm wondering if there's a better solution out there. I found that printing json_encode($xml) was different from json_encode($jobs) only in that the $jobs string needed a '{"Job": [xxx] }' wrapper, so I just sorta concatenated that stuff in there and it worked... but it feels so wrong!My PHP code is below; I'd love to know if anyone has any more elegant solutions!\[code\]// curls in rss feed$ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "https://overdriveinteractive.applicantstack.com/feed/jobs");curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);$output = curl_exec($ch);curl_close($ch);// loads xml$xml = simplexml_load_string($output, 'SimpleXMLElement', LIBXML_NOCDATA);// adds timestamp date field for sortingforeach($xml->Job as $job) { $job->addChild('date', strtotime($job->DateCreated));}// sorts xml$jobs = $xml->xpath('/Openings/Job');xsort($jobs, 'date', SORT_DESC);echo '{"Job":' . json_encode($jobs) . '}';function xsort(&$nodes, $child_name, $order=SORT_ASC) { $sort_proxy = array(); foreach ($nodes as $k => $node) { $sort_proxy[$k] = (string) $node->$child_name; } array_multisort($sort_proxy, $order, $nodes);}\[/code\]
 
Back
Top