2013-07-22 87 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