【问题标题】:XML parse with PHP - SimpleXML使用 PHP 解析 XML - SimpleXML
【发布时间】:2012-10-22 23:21:02
【问题描述】:

我有一个用 PHP SimpleXML 解析的 XML。我的 XML 文件的某些部分是这样的:

<deviceStatusPolling interval="60">
    <r:datapoint programmaticName="t_val_sys_pct_mssDbPartitionUsage" /> 
</deviceStatusPolling>

当我解析它时,我得到了:

Parsing 'deviceStatusPolling'...
    Has 1 attribute(s):
    - interval: 60

它不解析孩子:

    <r: datapoint programmaticName="t_val_sys_pct_mssDbPartitionUsage" />

这是解析函数:

function parse_recursive(SimpleXMLElement $element, $level = 0) {
$indent = str_repeat("\t", $level); // determine how much we'll indent

$value = trim((string) $element);  // get the value and trim any whitespace from the start and end
$attributes = $element->attributes();   // get all attributes
$children = $element->children();     // get all children

echo "{$indent}Parsing '{$element->getName()}'...<br>";
if(count($children) == 0 && !empty($value)) // only show value if there is any and if there aren't any children
{
    echo "{$indent}Value: {$element}<br>";
}

// only show attributes if there are any
if(count($attributes) > 0)
{
    echo $indent.'Has '.count($attributes).' attribute(s):<br>';
    foreach($attributes as $attribute)
    {
        echo "{$indent}- {$attribute->getName()}: {$attribute}<br>";
    }
}

// only show children if there are any
if(count($children))
{
    echo $indent.'Has '.count($children).' child(ren):<br>';
    foreach($children as $child)
    {
        parse_recursive($child, $level+1); // recursion :)
    }
}

echo $indent; // just to make it "cleaner"
echo "<br>";
}

这是 SimpleXML 的限制吗?还是我做错了什么?

问候

【问题讨论】:

  • 欢迎来到 SO!向我们展示您的代码/您如何打印它。
  • 另外,请告诉我们您对其印刷的期望。
  • 打印的内容和想要达到的效果并不明显。
  • 我想要实现的是打印属性interval-60和节点r:datapoint
  • 我们仍然看不到你在做什么来打印它——什么代码?打印?

标签: php xml-parsing


【解决方案1】:

你的问题不是很清楚,但可能需要这样的东西:

$xmlDoc = new SimpleXMLElement($docStr);
$allNamespaces = $xmlDoc->getNamespaces(true);
foreach ($allNamespaces as $nspace => $nurl) {
      $xmlDoc->registerXPathNamespace($nspace, $nurl);
}

阅读 SimpleXML 和命名空间。

这几乎肯定可以解决您的问题。看这里: http://blog.sherifmansour.com/?p=302

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多