2011-06-18 72 views
6

我真的不明白如何在PHP中使用SimpleXML。使用SimpleXML获取属性和值

这里是我的XML文件的为例:

<?xml version="1.0" encoding="UTF-8" ?> 
<eventlog version="1.1"> 

<event source="Firewall" timeStamp="1308433939" type="0" deleted="0" bodyLength="218"> 
<subject>Network access detected</subject> 
<action>Allowed</action> 
<message>The program c:\xampp\apache\bin\httpd.exe attempted to connect to the Internet. The program used the protocol TCP on port 80.</message> 
</event> 

</eventlog> 

我需要检索此: 来源,时间戳,主题,行动,信息

我只是不明白这一点。有人可以帮助我吗?

+0

问题是问题,答案是答案。我将你的编辑移动到下面的答案:http://stackoverflow.com/a/14194288/367456 - 如果你喜欢,你可以做同样的事情(从访问你的问题的历史),我会删除我的副本。 – hakre

回答

16

此代码应工作:

$xml = new SimpleXMLElement($xmlString); 
$source = $xml->event->attributes()->source; 
$timestamp = $xml->event->attributes()->timestamp; 
$subject = $xml->event->subject; 
$action = $xml->event->action; 
$message = $xml->event->message; 

...其中$的xmlString是XML文件的字符串。

阅读关于如何使用simpleXML here

希望这会有所帮助,祝你好运!

+0

哇!我没有想到这个!谢谢!但我有多个'事件'标签,:S,所以我只是把它放在foreach循环之间? –

+1

如果您想要获得所有事件标签下的所有主题,操作和消息,那么只需使用foreach循环即可。如果你只是想获得一个特定的事件,使用事件[0],事件[1]等。很高兴我帮助! –

1

为了教育你,我建议你看看PHP Docs on SimpleXML

虽然帮助你开始。

  1. 使用simplexml_load_file()simplexml_load_string()解析你的XML
  2. 这将返回一个对象 - 使用var_dump()print_r(),看看是什么样子。
  3. 遍历此对象以获取所需的属性。
+0

是的谢谢,我已经阅读了这个文档...但我会尝试使用var_dump和多个尝试我应该能够得到我想要的。谢谢:) –

1

尝试以下操作:

function time2DatetimeUS($timestamp) 
{ 
    $datetime = date('Y-m-d H:i:s', $timestamp); 
    return $datetime; 
} 

$db = new SQLiteDatabase("AutoAnalysis.sqlite", 0666, $err); 

$xml = new SimpleXMLElement($logs_antivirus_local, NULL, TRUE); 
foreach ($xml->event as $a) { 
    $source = $a->attributes()->source; 
    $timestamp = $a->attributes()->timeStamp; 
    $datetime = time2DatetimeUS("$timestamp"); 
    $subject = $a->subject; 
    $action = $a->action; 
    $message = $a->message; 
} 

$query = "INSERT INTO BitDefender(id, datetime, module, sujet, action, message) 
       VALUES ('', '$datetime', '$source', '$subject', '$action', '$message')"; 
$results = $db->queryexec($query); 
echo "  $datetime  $source $subject";