【问题标题】:How to get the simplexmlelement attributes values using php?如何使用 php 获取 simplexmlelement 属性值?
【发布时间】:2018-02-13 22:36:36
【问题描述】:

我有 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'];

            }

【问题讨论】:

  • 只需添加尝试上述代码时发生的情况。你有什么错误吗?你没有得到你想要的元素,但它运行了?
  • 如果您共享原始 XML 而不是 SimpleXMLElement 对象的转储会更容易。

标签: php xml svg


【解决方案1】:

一个关于如何使用 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>

【讨论】:

    猜你喜欢
    • 2017-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 1970-01-01
    • 2011-02-14
    相关资源
    最近更新 更多