开发者

Get child elements in xml with PHP

开发者 https://www.devze.com 2023-03-12 17:53 出处:网络
I have an xml file that I need to parse through and get values. Below is a snippit of xml <?xml version=\"1.0\"?>

I have an xml file that I need to parse through and get values. Below is a snippit of xml

    <?xml version="1.0"?>
<mobile>
  <userInfo>
  </userInfo>
  <CAT开发者_开发问答ALOG>
    <s0>
      <SUB0>
        <DESCR>Paranormal Studies</DESCR>
        <SUBJECT>147</SUBJECT>
      </SUB0>
    </s0>
    <sA>
      <SUB0>
        <DESCR>Accounting</DESCR>
        <SUBJECT>ACCT</SUBJECT>
      </SUB0>
      <SUB1>
        <DESCR>Accounting</DESCR>
        <SUBJECT>ACCTG</SUBJECT>
      </SUB1>
      <SUB2>
        <DESCR>Anatomy</DESCR>
        <SUBJECT>ANATOMY</SUBJECT>
      </SUB2>
      <SUB3>
        <DESCR>Anthropology</DESCR>
        <SUBJECT>ANTHRO</SUBJECT>
      </SUB3>
      <SUB4>
        <DESCR>Art</DESCR>
        <SUBJECT>ART</SUBJECT>
      </SUB4>
      <SUB5>
        <DESCR>Art History</DESCR>
        <SUBJECT>ARTHIST</SUBJECT>
      </SUB5>
    </sA> 

So, I need to grab all the child elements of <sA> and then there are more elements called <sB> etc

But I do not know how to get all of the child elements with <sA>, <sB>, etc.


How about this:

$xmlstr = LoadTheXMLFromSomewhere();

$xml = new simplexml_load_string($xmlstr);

$result = $xml->xpath('//sA');

foreach ($result as $node){
  //do something with node
}

PHP does have a nice class to access XML, which is called SimpleXml for a reason, consider heavily using that if your code is going to access only a part of the XML (aka query the xml). Also, consider doing queries using XPath, which is the best way to do it

Notice that I did the example with sA nodes only, but you can configure your code for other node types really easily.

Hope I can help!


you should look into simplexml_load_string() as I'm pretty sure it would make your life a lot easier. It returns a StdObject that you can use like so:

$xml = simplexml_load_string(<your huge xml string>);
foreach ($xml->hpt_mobile->CATALOG->sA as $value){
    // do things with sA children 
}


$xml = new DOMDocument();
        $xml->load('path_to_xml');
$htp = $xml->getElementsByTagName('hpt_mobile')[0];
$catalog = $htp->getElementsByTagName('CATALOG')[0]
$nodes = $catalog->getElementsByTagName('sA')->childNodes;
0

精彩评论

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