2011-07-26 75 views
0

我有這樣的XML文件:如何處理這個XML數據?

<images> 
<photo image="images/101.jpg" colorboxImage="images/101.jpg" colorboxInfo="Item 01" colorboxClass="image" url = "http://www.flashxml.net" target="_blank"> 
<![CDATA[<head>Hello</head><body>Welcome to the new Circular Gallery</body>]]></photo> 

<photo image="images/102.jpg" colorboxImage="images/102.jpg" colorboxInfo="Item 02" colorboxClass="image" url = "http://www.flashxml.net" target="_blank"> 
<![CDATA[<head>Download the new Circular Gallery</head><body>for FREE</body>]]></photo> 

<photo image="images/103.jpg" colorboxImage="images/103.jpg" colorboxInfo="Item 03" colorboxClass="image" url = "http://www.flashxml.net" target="_blank"> 
<![CDATA[<head>Insert it in your website</head><body>without any special skills or software</body>]]></photo> 

<photo image="images/104.jpg" colorboxImage="images/104.jpg" colorboxInfo="Item 04" colorboxClass="image" url = "http://www.flashxml.net" target="_blank"> 
<![CDATA[<head>Put your own images in the "images" folder</head><body>and update the images.xml file accordingly</body>]]></photo> 

<photo image="images/105.jpg" colorboxImage="images/105.jpg" colorboxInfo="Item 05" colorboxClass="image" url = "http://www.flashxml.net" target="_blank"> 
<![CDATA[<head>You can put <a href="http://www.flashxml.net" target="_blank">links</a> in this HTML/CSS formatted text</head><body>and you can also put links behind the images</body>]]></photo></images> 

這PHP代碼:

$xml = simplexml_load_file("images.xml"); 

foreach ($xml->children() as $child) 
    { 
    echo "Child node: " . $child . "<br />" . $child["image"] . "<br />"; 

    } 

,我得到的結果是這樣的:

Child node: HelloWelcome to the new Circular Gallery 
images/101.jpg 
Child node: Download the new Circular Galleryfor FREE 
images/102.jpg 
Child node: Insert it in your websitewithout any special skills or software 
images/103.jpg 

我想在這部分分隔文本:

<![CDATA[<head>You can put <a href="http://www.flashxml.net" target="_blank">links</a> in this HTML/CSS formatted text</head><body>and you can also put links behind the images</body>]]> 

我想讀頭部分和身體部分的文字,但是這段代碼會將它們合併成一段文字,而我無法知道如何得到每一段文字並做我需要做的事情

+0

這是一個CDATA部分。任何內容都被視爲文字字符串。 – Gordon

回答

0

看起來您必須再次解析節點內容(使用simplexml_load_string)。但我在SimpleXMLElement找不到功能來檢索節點的文本內容,只有子元素。奇怪。

但它看起來像轉換到一個節點返回該節點內容的字符串,因此你可以試試這個:

$xml = simplexml_load_file("images.xml"); 

foreach ($xml->children() as $child) 
{ 
    echo "Child node: " . $child . "<br />" . $child["image"] . "<br />"; 
    $content = simplexml_load_string("<dummy>". $child . "</dummy>"); 
    echo "child head: " . $content->head . "<br/>"; 
    echo "child body: " . $content->body . "<br/>"; 
}