引用網址
https://gist.github.com/tfnet/2037443
PHP 使用 simplexml_load_string() 解析 XML 資料,
要一直 $node->children() 一個節點一個節點的取,這樣用實在很麻煩,
如果能一次把 XML 結構資料轉成 Array 在讀裡面的資料就非常好用了,
網路查了一下看到神人分享的function,完全用原本的XML結構打造成Array,非常好用,
該網址提供的程式碼較適用於Class中,我做了一點小小的修改,
原版本請連文章上方引用網址,修改後版本請於文章下方 Download
<?php
/**
* Converts a simpleXML element into an array. Preserves attributes.<br/>
* You can choose to get your elements either flattened, or stored in a custom
* index that you define.<br/>
* For example, for a given element
* <code>
* <field name=”someName” type=”someType”/>
* </code>
* <br>
* if you choose to flatten attributes, you would get:
* <code>
* $array[‘field’][‘name’] = ‘someName’;
* $array[‘field’][‘type’] = ‘someType’;
* </code>
* If you choose not to flatten, you get:
* <code>
* $array[‘field’][‘@attributes’][‘name’] = ‘someName’;
* </code>
* <br>__________________________________________________________<br>
* Repeating fields are stored in indexed arrays. so for a markup such as:
* <code>
* <parent>
* <child>a</child>
* <child>b</child>
* <child>c</child>
* …
* </code>
* you array would be:
* <code>
* $array[‘parent’][‘child’][0] = ‘a’;
* $array[‘parent’][‘child’][1] = ‘b’;
* …And so on.
* </code>
* @param simpleXMLElement $xml the XML to convert
* @param boolean|string $attributesKey if you pass TRUE, all values will be
* stored under an ‘@attributes’ index.
* Note that you can also pass a string
* to change the default index.<br/>
* defaults to null.
* @param boolean|string $childrenKey if you pass TRUE, all values will be
* stored under an ‘@children’ index.
* Note that you can also pass a string
* to change the default index.<br/>
* defaults to null.
* @param boolean|string $valueKey if you pass TRUE, all values will be
* stored under an ‘@values’ index. Note
* that you can also pass a string to
* change the default index.<br/>
* defaults to null.
*
* @return array the resulting array.
*/
function simpleXMLToArray($xml,$attributesKey=NULL,$childrenKey=NULL,$valueKey=NULL)
{
if($childrenKey && !is_string($childrenKey)){
$childrenKey = ‘@children’;
}
if($attributesKey && !is_string($attributesKey)){
$attributesKey = ‘@attributes’;
}
if($valueKey && !is_string($valueKey)){
$valueKey = ‘@values’;
}
$return = array();
$name = $xml->getName();
$_value = trim((string)$xml);
if(!strlen($_value)){
$_value = null;
};
if($_value!==null){
if($valueKey){
$return[$valueKey] = $_value;
}
else{$return = $_value;
}
}
$children = array();
$first = true;
foreach($xml->children() as $elementName =&g[……]