使用SimpleXML获取属性和值

时间:2011-06-18 23:20:15

标签: php attributes simplexml

我真的不明白如何在PHP中使用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>

我需要检索这个: 来源,时间戳,主题,行动,消息

我只是不明白。有人可以帮帮我吗?

3 个答案:

答案 0 :(得分:17)

此代码应该有效:

$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

希望这有帮助并祝你好运!

答案 1 :(得分:1)

为了教你钓鱼,我建议你查看PHP Docs on SimpleXML

帮助你开始。

  1. 使用simplexml_load_file()simplexml_load_string()解析XML
  2. 这将返回一个对象 - 使用var_dump()print_r()来查看它的外观。
  3. 遍历此对象以获取所需的属性。

答案 2 :(得分: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";