2012-10-01 31 views
0

我需要從PHP中的節點數組中自動創建GEXF(http://gexf.net)XML文件。如何從PHP創建GEXF?

我google了這個話題,但無法找到有用的東西。

我該怎麼做?

+0

我並不知道GEXF的任何lib,但您可以隨時使用任何通用的XML擴展,例如http://stackoverflow.com/questions/188414/best-xml-parser-for-php/3616044#3616044 – Gordon

+0

我真的想避免寫我自己的。從複雜的節點網絡構建這樣的XML並不容易。 – thedp

回答

3

這是我對此的看法。幾個小時後,我明白了。這個例子也支持viz:namespace,所以你可以使用更詳細的節點元素和佈局。

// Construct DOM elements 
$xml = new DomDocument('1.0', 'UTF-8'); 
$xml->formatOutput = true; 
$gexf = $xml->createElementNS(null, 'gexf'); 
$gexf = $xml->appendChild($gexf); 

// Assign namespaces for GexF with VIZ :) 
$gexf->setAttribute('xmlns:viz', 'http://www.gexf.net/1.1draft/viz'); // Skip if you dont need viz! 
$gexf->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); 
$gexf->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'schemaLocation', 'http://www.gexf.net/1.2draft http://www.gexf.net/1.2draft/gexf.xsd'); 

// Add Meta data 
$meta = $gexf->appendChild($xml->createElement('meta')); 
$meta->setAttribute('lastmodifieddate', date('Y-m-d')); 
$meta->appendChild($xml->createElement('creator', 'PHP GEXF Generator v0.1')); 
$meta->appendChild($xml->createElement('description', 'by me etc')); 

// Add Graph data! 
$graph = $gexf->appendChild($xml->createElement('graph')); 
$nodes = $graph->appendChild($xml->createElement('nodes')); 
$edges = $graph->appendChild($xml->createElement('edges')); 

    // Add Node! 
    $node = $xml->createElement('node'); 
    $node->setAttribute('id', '1'); 
    $node->setAttribute('label', 'Hello world!'); 

     // Set color for node 
     $color = $xml->createElement('viz:color'); 
     $color->setAttribute('r', '1'); 
     $color->setAttribute('g', '1'); 
     $color->setAttribute('b', '1'); 
     $node->appendChild($color); 

     // Set position for node 
     $position = $xml->createElement('viz:position'); 
     $position->setAttribute('x', '1'); 
     $position->setAttribute('y', '1'); 
     $position->setAttribute('z', '1'); 
     $node->appendChild($position); 

     // Set size for node 
     $size = $xml->createElement('viz:size'); 
     $size->setAttribute('value', '1'); 
     $node->appendChild($size); 

     // Set shape for node 
     $shape = $xml->createElement('viz:shape'); 
     $shape->setAttribute('value', 'disc'); 
     $node->appendChild($shape); 

    // Add Edge (assuming there is a node with id 2 as well!) 
    $edge = $xml->createElement('edge'); 
    $edge->setAttribute('source', '1'); 
    $edge->setAttribute('target', '2');  

// Commit node & edge changes to nodes! 
$edges->appendChild($edge); 
$nodes->appendChild($node); 

    // Serve file as XML (prompt for download, remove if unnecessary) 
    header('Content-type: "text/xml"; charset="utf8"'); 
    header('Content-disposition: attachment; filename="internet.gexf"'); 

// Show results! 
echo $xml->saveXML(); 

吃你的心臟了!隨意給我發電子郵件您的項目結果,我很好奇。