2013-07-22 88 views
0

不太確定我在做什麼解析/讀取xml文檔時出錯。 我的猜測是它不是標準化的,我需要一個不同的過程來從字符串中讀取任何東西。PHP - 解析,讀取XML

如果是這樣的話,那麼我很高興看到有人會讀這個xml。 這就是我所擁有的,以及我在做什麼。

的example.xml

<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="someurl.php"?> 
<response> 
<status>Error</status> 
<error>The error message I need to extract, if the status says Error</error> 
</response> 

read_xml.php

<?php 
$content = 'example.xml'; 
$string = file_get_contents($content); 
$xml = simplexml_load_string($string); 
print_r($xml); 
?> 

我越來越沒有結果從print_r回來。
我切換xml的東西更多的標準,如:

<?xml version="1.0" encoding="ISO-8859-1"?> 
<note> 
<to>Tove</to> 
<from>Jani</from> 
<heading>Reminder</heading> 
<body>Don't forget me this weekend!</body> 
</note> 

...它工作得很好。所以我相信這是由於非標準格式,從我從中獲得的源代碼傳回的。

我將如何提取<status><error>標籤?

回答

0

泰克有一個很好的答案,但如果你想使用SimpleXML,你可以嘗試這樣的事:

<?php 

$xml = simplexml_load_file('example.xml'); 
echo $xml->asXML(); // this will print the whole string 
echo $xml->status; // print status 
echo $xml->error; // print error 

?> 

編輯:如果你的XML中有多個<status><error>標籤,看看這個:

$xml = simplexml_load_file('example.xml'); 
foreach($xml->status as $status){ 
    echo $status; 
} 
foreach($xml->error as $error){ 
    echo $error; 
} 

我假設<response>是你的根。如果不是,請嘗試$xml->response->status$xml->response->error

0

我更喜歡使用PHP的DOMDocument類。

嘗試這樣:

<?php 

$xml = '<?xml version="1.0" encoding="UTF-8"?> 
<?xml-stylesheet type="text/xsl" href="someurl.php"?> 
<response> 
<status>Error</status> 
<error>The error message I need to extract, if the status says Error</error> 
</response>'; 

$dom = new DOMDocument(); 
$dom->loadXML($xml); 

$statuses = $dom->getElementsByTagName('status'); 
foreach ($statuses as $status) { 
    echo "The status tag says: " . $status->nodeValue, PHP_EOL; 
} 
?> 

演示:http://codepad.viper-7.com/mID6Hp