簡體   English   中英

使用php選擇XML文件中根節點的第一個子節點

[英]select first child node of root node in XML file using php

我是XML的新手,到目前為止設法在php中使用它來獲取XML的根節點...

function xmlRootNode($xmlfile){
    $xml = simplexml_load_string(file_get_contents($xmlfile));
    $xml = $xml->getName();
    echo $xml;
}

我現在想要做的是使用該根節點找出其子節點的名稱。 例如,具有以下內容的文件將使用上述函數輸出“food”作為根。 我現在如何使用它來返回其子名稱'fruit'?

<food>
  <fruit>
    <type>apples</type>
  </fruit>
</food>

最終我要做的是找出根節點的子節點名稱,這樣我就可以在另一個計算有多少節點的函數中使用它。 谷歌搜索和搞亂不同的想法,但認為我錯過了一個簡單的過程,所以任何想法將不勝感激。

嘗試

/* get list of fruits under food */
$fruits = $xml->children();

/* or treat the $xml as array */
foreach ($xml as $fruit)
{
   /* your processing */
}

另外,以下是多余的,

$xml = simplexml_load_string(file_get_contents($xmlfile));

切換到

$xml = simplexml_load_file($xmlfile);
// The following code block illustrates how you can get at the name of each child
$columnCDValues = array();
foreach ($simpleXMLElement->profile->children() as $child)
{
    $name = $child->getName();
    $value = $simpleXMLElement->profile->$name;         
    $columnCDValues[$child->getName()] = $value;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM