Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get attributes and values using SimpleXML

I really don't understand how to use SimpleXML in PHP.

Here is an exemple of my XML file:

<?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>

I need to retrieve this: Source, Timestamp, Subject, Action, Message

I just don't get it. Can someone please help me with this?

like image 754
Jeremy Dicaire Avatar asked Jun 18 '11 23:06

Jeremy Dicaire


3 Answers

This code should work:

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

... where $xmlString is the string of the xml file.

Read up on how to use simpleXML here.

Hope this helped and good luck!

like image 140
Jeff Gortmaker Avatar answered Nov 05 '22 14:11

Jeff Gortmaker


In the interest of teaching you to fish, I'd encourage you to check out the PHP Docs on SimpleXML.

To help get your started though.

  1. Use simplexml_load_file() or simplexml_load_string() to parse your XML
  2. This will return an object - use var_dump() or print_r() to see what it looks like.
  3. Traverse this object to obtain the attributes you want.
like image 29
Jason McCreary Avatar answered Nov 05 '22 16:11

Jason McCreary


Try the following:

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";
like image 1
hakre Avatar answered Nov 05 '22 16:11

hakre