2012-09-08 86 views
1

我已經用PHP中的'simplexml_load_file'加載了一個XML文件,現在我想從它讀取一些元素以使用PHP打印出來。我發現並沒有導致成功,因爲我的XML文件也許是太複雜了所有的方法......我發現的最好的事情是:在PHP中使用非常複雜的XML文件(SimpleXML)

Just wanted to add a post as to how you can extract the value from a SimpleXMLElement. Its not as straightforward as you think. Because its a complex object you can't just access the element directly. Here is a sample of data that represents a var_dump of a SimpleXmlElement

array(1) { [0]=> object(SimpleXMLElement)#13 (2) { ["@attributes"]=> array(1) { ["name"]=> string(5) "title" } [0]=> string(19) "PHP Tech Book" } }

If you want to extract the title of the book you have to cast the specified element to a string like so. $newTitle = (string) $title[0];

The $title variable is the SimpleXMLElement that you have extracted from the xml document using simplexml_load_string for instance. To initially access the title element from the xml document you can do like so, using xpath. $title = $doc->xpath('str[@name="title"]');

Hope this helps someone out there.

我試圖用「$稱號= $ doc-> xpath('str [@ name =「title」]');「用我自己的XML文件,用我自己的元素替換它,但後來我得到一個PHP錯誤:

A PHP Error was encountered Severity: Notice Message: Array to string conversion Filename: views/welcome_message.php Line Number: 79

這是我的代碼:

<?php 
    if (file_exists('data.xml')) { 
     $xml = simplexml_load_file('data.xml'); 

    $title = $xml->xpath('str[@name="name"]'); 
    echo $title; 

    } else { 
     exit('Failed to open test.xml.'); 
    } 
    ?> 

這是我非常混亂的XML文件的一點點提取物:

SimpleXMLElement Object ([folder] => SimpleXMLElement Object ( [@attributes] => Array ([name] => ABC) [file] => SimpleXMLElement Object ([@attributes] => Array ([name] => DEF [size] => 123 [creation-time] => 03.09.2012 16:36:59 [last-write-time] => 06.09.2012 10:46:39 [id3v2] => 1 [v2-tag-PRIV] => XMP ; WM/MediaClassSecondaryID; WM/MediaClassPrimaryID ?}`?#??K??H?*(D; WM/Provider A M G; WM/WMContentID [email protected]??B????; WM/WMCollectionID ?Yd??B??N5 ?; WM/WMCollectionGroupID ]?????N?????^e; WM/UniqueFileIdentifier A M G a _ i d = R 2 0 5 6 3 8 9 ; A M G p _ i d = P 2 6 4 5 ; A M G t _ i d = T 2 2 1 6 6 0 0 3 [v2-track] => 2 [v2-song-title] => FGH [v2-album] => IJK [v2-genre] => (12) [v2-tag-TPUB] => LMN [v2-tag-TYER] => 1997 [v2-tag-TPE2] => OPQ [v2-composer] => RST [v2-artist] => UVW [id3v1] => 1 [song-title] => XYZ [artist] => ARTIST1 [album-title] => TITLE1 [year] => 1997 [comment] => [track] => 2 [genre] => Other [mpeg-version] => 1 [mpeg-layer] => 3 [bitrate] => 320Kbps [sampling-rate] => 48000Hz [channel-mode] => JointStereo))

爲什麼有一個「@」在[@屬性],如何要處理呢?我如何從不同的元素獲取信息?

回答

0

SimpleXML ->xpath() function返回一個SimpleXML對象數組,每個對象表示與您的XPath表達式匹配的元素或屬性。所以首先,你需要循環的結果(或採取第一個[0]);其次,您需要對發現的SimpleXML對象進行一些操作。如果是屬性,(string)$sx_attrib會給你它的價值;否則,您需要進一步操作。

最後,請勿在SimpleXML對象上使用var_dump,print_rvar_export,因爲它們不是「真正的」PHP對象,而是非PHP數據的包裝。改爲使用simplexml_dump

0

當我不得不面對'沉重的'dom操縱時,我總是使用simple_html_dom。 試一試,也許它有幫助!