Jump to content

advice on parsing xmlns with php


turnin
Go to solution Solved by requinix,

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
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);
?>
Edited by ignace
Added code tags
Link to comment
Share on other sites

  • Solution

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 .

Edited by requinix
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.