简体   繁体   中英

Parsing XML with php to Array

I've tried to parse a XML String with php.

The example of XML is

<?xml version="1.0"?>
<root>
    <Log>
        <Item>
            <name>![CDATA[James]]</name>
            <address>![CDATA[Korea]]</address>
            <email>![CDATA[Korea@gmail.com]]</email>
        </Item>
        <Item>
            <name>![CDATA[James2]]</name>
            <address>![CDATA[Korea2]]</address>
            <email>![CDATA[Korea@gmail.com2]]</email>
        </Item>
    </Log>
</root>

My Parsing PHP Code is

$xml = simplexml_load_string($input,null,LIBXML_NOCDATA);
$xml=json_decode( json_encode( $xml),true);

However, When I try to get sizeof($xml['Log']['Item']), have some problems.

If XML have One 'Item' , then sizeof($xml['Log']['Item']) return '3' .

but If XML have 4 'Item's , then it return '4'.

I want to return 1, if XML have One 'Item'.

How can I solve this problem.?

I solved this parsing problem with foreach().

$xml = simplexml_load_string($input,null,LIBXML_NOCDATA);
$itemArray=$xml->Log->Item;
$i=0;
$sqlParamArray= array();
foreach ($itemArray as $tag) {
 $name= trim($tag->name);
 $address= trim($tag->address);
 $email= trim($tag->email);
  array_push($sqlParamArray,$name,$address,$email);
  $i++;
}
echo $i;

....

sizeof('Item') is saved in $i.

I solved it.

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