Jump to content

advice on parsing xmlns with php


turnin

Recommended Posts

OK, I admit I'm a total newbie but been reading all day and making no progress in understanding.

I have a script that calls an api, that api returns xml, like so https://dl.dropbox.com/u/40331447/samplereturn.xml

I've tried SimpleXML and it fails as the return contains namespaces, I think.

I will run this script once per hour for eg:

 

I want to be able to send this to my mysql database and I'll eventually I'll query it based on the location fields

What would be the easiest php method or library to parse this, so that each database entry is stored like so:

 

( from Parent_<tns:motorways> tns:name), (fromchild <tns:Locations> <tns:name>, <tns:congestion>, <Tns:direction>,<tns:lat>,<tns:lng> etc

So the parent is in each entry along with each iteration of the children.

 

Hope that makes sence , any help is really appreciated !

Cheers

James.

 

Link to comment
https://forums.phpfreaks.com/topic/275914-advice-on-parsing-xmlns-with-php/
Share on other sites

<?php
$handle = curl_init();
curl_setopt($handle, CURLOPT_URL, '[url=https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TrafficConditions2/REST/FeedService/]https://infoconnect1.highwayinfo.govt.nz/ic/jbi/TrafficConditions2/REST/FeedService/[/url]');
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_HTTPHEADER, array ('username:xxxx' , 'password: xxxx'));

$response = curl_exec($handle);
curl_close($handle);
$xml = new SimpleXML($response);
$motorway=$xml -> 'tns:motorways'
//print_r($response);
print_r($motorway);
?>

SimpleXML only allows you to work in a single namespace in a time. It starts in the empty namespace (xmlns="") so if you do $xml->motorways it will try to find a in that namespace. Which doesn't exist in your XML.

Use children to switch namespaces.

$motorways = $xml->children("tns", true)->trafficConditions->motorways;
(You don't need to children() every time after, only the first time really just to change the namespace.)

 

[edit] is a child of . You have to go through that first. Also note that there may be more than one .

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.