2010-11-22 99 views
0

大家好我有一個XML文件,例如解析嵌套的XML到PHP

<recipe> 
    <id>abc</id> 
    <name>abc</name> 
    <instructions> 
     <instruction> 
      <id>abc</id> 
      <text>abc</text> 
     </instruction> 
     <instruction> 
      <id>abc2</id> 
      <text>abc2<text> 
     <instruction> 
    <instructions> 
<recipe> 

在我的php文件我用

$url = "cafe.xml"; 
// get xml file contents 
$xml = simplexml_load_file($url); 

// loop begins 
foreach($xml->recipe as $recipe) 
{ 
code; 
} 

但它只能檢索配方ID和名稱,以便我如何可以檢索說明。

+0

也許在代碼中,你必須訪問$ recipe->指令或類似的東西? – Eineki 2010-11-22 08:01:18

回答

3

你應該能夠做到這一點:

foreach($xml->recipe as $recipe) { 
    foreach($recipe->instructions->instruction as $instruction) { 
     // e.g echo $instruction->text 
    } 
} 

如果recipe是你的根結點,它應該是這樣的:

foreach($xml->instructions->instruction as $instruction) { 
    // e.g echo $instruction->text 
} 

看一看other examples.

3

這裏有一個函數將有效的XML轉換爲PHP數組:

/** 
* Unserializes an XML string, returning a multi-dimensional associative array, optionally runs a callback on 
* all non-array data 
* 
* Notes: 
* Root XML tags are stripped 
* Due to its recursive nature, unserialize_xml() will also support SimpleXMLElement objects and arrays as input 
* Uses simplexml_load_string() for XML parsing, see SimpleXML documentation for more info 
* 
* @param mixed $input 
* @param callback $callback 
* @param bool $_recurse used internally, do not pass any value 
* @return array|FALSE Returns false on all failure 
*/ 
function xmlToArray($input, $callback = NULL, $_recurse = FALSE) 
{ 
    // Get input, loading an xml string with simplexml if its the top level of recursion 
    $data = ((!$_recurse) && is_string($input)) ? simplexml_load_string($input) : $input; 

    // Convert SimpleXMLElements to array 
    if ($data instanceof SimpleXMLElement) { 
     $data = (array) $data; 
    } 

    // Recurse into arrays 
    if (is_array($data)) foreach ($data as &$item) { 
     $item = xmlToArray($item, $callback, TRUE); 
    } 

    // Run callback and return 
    return (!is_array($data) && is_callable($callback)) ? call_user_func($callback, $data) : $data; 
} 
+1

如果將XML轉換爲數組,該函數可能應該稱爲'xmlToArray'或類似的:-) – richsage 2012-08-02 08:58:10