This is my first post on Stack Overflow and I have to say I've found this site to be a gold mine of answers! So, first post is a little bit noobish- there's a lot of answers on roughly the topic but can't seem to fit them to my exact problem. The code that accesses the XML using namespaces works and is pretty neat, so might help anyone trying to figure THAT bit out...
I have an XML file that I'm reading:
<?xml version='1.0'?>
<epp xmlns="urn:ietf:params:xml:ns:epp-1.0" xmlns:domain="urn:ietf:params:xml:ns:domain-1.0" xmlns:ext-domain="http://ift.tt/1Aj0Hn8">
<response>
<result code='1000'>
<msg>Command completed successfully</msg>
</result>
<resData>
<domain:chkData>
<domain:cd>
<domain:name avail="1">foo.com</domain:name>
</domain:cd>
<domain:cd>
<domain:name avail="0">foo.net</domain:name>
<domain:reason>registered</domain:reason>
</domain:cd>
<domain:cd>
<domain:name avail="0">foo.org</domain:name>
<domain:reason>unknown</domain:reason>
</domain:cd>
<domain:cd>
<domain:name avail="0">foo.plumbing</domain:name>
<domain:reason>c:category7</domain:reason>
</domain:cd>
<domain:cd>
<domain:name avail="1">foo.uk</domain:name>
<domain:reason>qualified</domain:reason>
</domain:cd>
</domain:chkData>
</resData>
<extension>
<ext-domain:categorisedChkData>
<ext-domain:cd>
<ext-domain:name price="1050.37">foo.plumbing</ext-domain:name>
</ext-domain:cd>
</ext-domain:categorisedChkData>
</extension>
<trID>
<clTRID>6f2d7447511677c62631e4bdb9563172</clTRID>
<svTRID>test-da76f89aacec9861b89bf093fc120566</svTRID>
</trID>
</response>
</epp>
I want to be able to get access to the children of domain:cd. See comments in the code below
$xml = simplexml_load_string($return_xml, NULL, NULL, "urn:ietf:params:xml:ns:epp-1.0");
$xml->registerXPathNamespace('domain', 'urn:ietf:params:xml:ns:domain-1.0');
$xml->registerXPathNamespace('ext-domain', 'http://ift.tt/1Aj0Hn8');
// I can list out the domain:name elements and attributes nicely.
foreach ($xml->xpath('//domain:name') as $domain){
echo '<p>Domain: '.$domain.'<br/>'; // Works
echo 'avail-code: '.$domain['avail'].'<br/>'; // Works
echo '</p>';
}
// And I can list out the domain:reason elements afterwards.
foreach ($xml->xpath('//domain:reason') as $reason){
echo '<p>Reason: '.$reason.'<br/>'; // Works
echo '</p>';
}
// But what I want, is to be able to get to them both from the same node in the order I need them.
// A little like this, so that I can form some content.
$res = $xml->xpath('//domain:cd');
foreach ($res->children() as $node){
echo '<p>Name: '.$node['domain:name'].'<br/>'; // this is wrong, mind.
echo 'Reason: '.$node['domain:reason'].'<br/>'; // this is wrong, mind.
echo '</p>';
}
It seems a little wasteful and fiddly to have to run separate xpath queries to get each bit of data, I should be able to access the node's children (domain:name, domain:reason) but the solution is a little elusive, especially with the additional complication of namespaces.
Thanks folks. :)
No comments:
Post a Comment