简体   繁体   中英

SimpleXML and PHP

I have a quick question on this, I've seen other posts and they still didn't really help with this particular xml navigation I am trying to do between the XML objects.

The XML output is as follows (data is stripped, but the structure is there, still):

<hashtable>
 <entry>
  <string>+++++++1+++++++</string>
   <hashtable>
    <entry>
      <string></string>
      <string>DATA I WANT TO RETRIEVE IS HERE</string>
    </entry>
    <entry>
      <string></string>
      <boolean></boolean>
    </entry>
    <entry>
      <string></string>
      <string></string>
    </entry>
   </hashtable>
  </entry>
</hashtable>

I can not for the life of me get this to work.

I have tried something similar to $xml->entry['0']->string and I received the string that I labeled +++++++1+++++++ in the above XML response. I don't know how to get to what I am wanting, which is the string I labeled DATA I WANT TO RETRIEVE IS HERE .

My simplexml_load_file(#) is called by $xml ;

Can anyone possibly provide an easy way to understand how i can retrieve the data in the string I labeled as DATA I WANT TO RETRIEVE IS HERE ? How should I go about retrieving this particular <string></string> ?

You should look up xPath at http://au1.php.net/manual/en/simplexmlelement.xpath.php
Something along the line of this:

...    
$xml = new SimpleXMLElement($string);

$result = $xml->xpath('/hashtable/entry/hashtable/entry/string');

while(list( , $node) = each($result)) {
    echo '/hashtable/entry/hashtable/entry/string: ',$node,"\n";
}
...

Please note - the xPath used will give all nodes that match (more than you intended...)

Try this, the trick is to convert the Object back to string by adding a '':

        $a = "<hashtable>
     <entry>
      <string></string>
       <hashtable>
        <entry>
          <string></string>
          <string>DATA I WANT TO RETRIEVE IS HERE</string>
        </entry>
        <entry>
          <string></string>
          <boolean></boolean>
        </entry>
        <entry>
          <string></string>
          <string></string>
        </entry>
       </hashtable>
      </entry>
    </hashtable>";

    $xml = simplexml_load_string($a);
    echo  $xml->entry->hashtable->entry[0]->string[1].''; //print DATA I WANT TO RETRIEVE IS HERE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM