【问题标题】:Get attributes and values using SimpleXML使用 SimpleXML 获取属性和值
【发布时间】:2011-09-17 23:24:38
【问题描述】:

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

我需要检索这个: 来源、时间戳、主题、操作、消息

我只是不明白。有人可以帮我解决这个问题吗?

【问题讨论】:

  • 问题就是问题,答案就是答案。我将您的编辑移到下面的答案中:stackoverflow.com/a/14194288/367456 - 如果您愿意,您也可以这样做(通过访问您的问题的历史记录),然后我将删除我的副本。

标签: php attributes simplexml


【解决方案1】:

为了教你钓鱼,我鼓励你查看PHP Docs on SimpleXML

不过,为了帮助您入门。

  1. 使用simplexml_load_file()simplexml_load_string() 解析您的XML
  2. 这将返回一个对象 - 使用 var_dump()print_r() 查看它的外观。
  3. 遍历这个对象,获取你想要的属性。

【讨论】:

  • 是的,谢谢,我已经阅读了这个文档...但是我会尝试使用 var_dump 并且通过多次尝试我应该能够得到我想要的。谢谢:)
【解决方案2】:

这段代码应该可以工作:

$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

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

【讨论】:

  • 哇!我没想到!谢谢!但我有多个“事件”标签,:S 所以我只是把它放在 foreach 循环之间?
  • 如果您想获取所有事件标签下的所有主题、操作和消息,那么是的,只需使用 foreach 循环。如果您只想获取特定事件之一,请使用 event[0]、event[1] 等。很高兴我提供了帮助!
【解决方案3】:

尝试以下方法:

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";

【讨论】:

    猜你喜欢
    • 2012-10-03
    • 2017-03-14
    • 2018-08-04
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多