开发者

simpleXML node access by index prob!em

I am receiving an XML response based on a request I place to a server and it does in fact return a valid set of results that I can dump on the screen using print_r() Result set looks like this(edit: this is the exact structure of the file):

<root>  
     <main_node1>  
         <value1>one</value1>  
         <value2>two</value2>  
     </main_node1>  
     <main_node2>  
         <anothervalue>whatever</anothervalue>  
     </main_node2>  
     <recordset>  
        <record>  
            <value1>one</value1>  
            <value2>two</value2>  
        </reocrd>  
        <record>  
            <value1>one</value1>  
            <value2>two</value2>  
        </reocrd>  
        <record>  
            <value1>one</value1>  
            <value2>two</value2>  
        </reocrd>  
     </recordset>  
</root>

when I use the line:

$xml = simplexml_load_string($xmlRequest);
$records = $xml->recordset->record;  

I can walk through the $records array with a foreach loop without any problems however, when I try to access a specific record within the recordset using an index such as

$record = $xml->recordset->record[$index];  

I am getting a NULL valeu back. I also tried to cast the result into an (array) with no success so far.

Every document I looked at regarding simpleXML says that it is p开发者_如何学JAVAossible to access the XML node by index, can someone please tell me what I might be doing wrong here?

Edit: so recordset is not the root of the document yet I am able to use the $xml->recordset->record notation to load a list of records in to my $records variable and print it out using the foreach loop.


I resolved my issue by using

$records = $xml->xpath('//record'); 

notation and I am now able to access any record by their index.

Thank you for trying, I appreciate your efforts.


You're not getting anything back because the 'recordset' node is the root of your $xml variable (not sure if I'm describing this correctly).

This should work:

<?php
    //Example xml, replace this with $xml = simplexml_load_string($xmlRequest);
    $xml = simplexml_load_string('<?xml version="1.0"?>
    <recordset><record><value1>one</value1><value2>two</value2></record>
    <record><value1>one</value1><value2>two</value2></record>
    </recordset>');

    $record = $xml->record[0];
    print_r ($record);

?>


Another way to do it, without using xpath is:

Using this as base:

 $record = $xml->recordset->record[$index];

You got to make index as int, for some reason just receiving it does not work. So:

$index = trim($_GET['index']);
$index = intval($index);

Now this will work:

 $record = $xml->recordset->record[$index];

Best Regards, RaphaelDDL

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜