如何用PHP创建GEXF?

时间:2012-10-01 17:37:15

标签: php xml graph

我需要从PHP中的节点数组自动创建GEXF(http://gexf.net)XML文件。

我用谷歌搜索了这个主题,却找不到任何有用的东西。

我该怎么做?

1 个答案:

答案 0 :(得分: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();

吃掉你的心!请随时给我发送您的项目结果,我很好奇。

相关问题