如何使用php获取simplexmlelement属性值?

时间:2017-09-05 15:08:42

标签: php xml svg

我有simplexml元素对象,它呈现了foreach结果的输出。我必须从输出中提取值。

到目前为止,我试图循环simplexmlelement个对象。我正在从给定的输出中形成svg元素。这些输出来自另一个foreach循环结果。

[g] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [id] => 0.2922376764472574
                )

            [text] => SimpleXMLElement Object
                (
                    [@attributes] => Array
                        (
                            [fill] => #000000
                            [stroke] => none
                            [stroke-width] => 0
                            [stroke-linecap] => round
                            [stroke-linejoin] => round
                            [x] => 65
                            [y] => 85
                            [text-anchor] => middle
                            [font-size] => 90.75
                            [font-family] => Twine
                            [data-textcurve] => 0
                            [data-itemzoom] => 1 1
                        )

                    [tspan] => Tetst
                )

        )


for ($i = 0; $i < count($result); $i++)
            {
                //var_dump( $result[$i] );
                //$op .= '<g id="0.8354780427180231">';

                print_r($result[$i]);

                echo "testsdf";print_r($result[$i]->g['text']);

                echo 'test<g id="'.$result[$i]->g['id'].'"><text fill="'.$result[$i]->text->attributes()->fill.'" stroke="none" stroke-width="0" stroke-linecap="round" stroke-linejoin="round" x="65" y="85" text-anchor="middle" font-size="90.75" font-family="Twine" data-textcurve="0" data-itemzoom="1 1">'.$result[$i]->text['tspan'].'</text>';

                echo "</g>";
                echo $result[$i]->g->text['font-family'];

            }

1 个答案:

答案 0 :(得分:0)

使用SimpleXML如何使用结构和访问文档各个部分的一个小例子。

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$html = "<body>
<g id='0.2922376764472574'>
<text fill='#000000' stroke='none' stroke-width='0'>
<tspan>Tetst</tspan>
</text>
</g>
</body>";

$doc = simplexml_load_string($html);

foreach ( $doc->g as $tag)  {
    echo "<g id='".$tag['id']."'>";   
    echo "<text fill='".$tag->text['fill']."'>";
    echo $tag->text->tspan;
    echo "</text>";
    echo "</g>";
}

我必须对您的XML内容做出假设,但我希望这已经足够了。

我基于循环遍历文档根目录下的所有标记。如果不是这种情况,您可以将其更改为...

foreach ($result as $tag)

如果您(例如)从XPath查询中获取这些内容,它应该做同样的事情。

我已经取出了一些属性,但它只是重复相同逻辑的一种情况,访问每个属性就好像它是一个关联数组元素。

测试样本的输出是......

<g id='0.2922376764472574'><text fill='#000000'>Tetst</text></g>
相关问题