2015-07-19 34 views
0

因此,我想通过属性来遍历XML,然后从协调标记中打印标记。这是结构:使用XPath和PHP存储XML文档时,标记信息未按需要存储在数组中

<emp salesid="1"> 
    <report>07-14-2015_DPLOH_SalesID_1.pdf</report> 
    <report>07-17-2015_DPLOH_SalesID_1.pdf</report> 
    <report>07-14-2015_DTE_SalesID_1.pdf</report> 
    <report>07-14-2015_IDT_SalesID_1.pdf</report> 
    <report>07-14-2015_Kratos_SalesID_1.pdf</report> 
    <report>07-14-2015_Spark_SalesID_1.pdf</report> 
</emp> 

这里是我的代码:

$xml = new SimpleXMLElement($xmlStr); 

foreach($xml->xpath("//emp/report") as $node) { 
    //For all found nodes retrieve its ID from parent <emp> and store in $arr 
    $id = $node->xpath("../@salesid"); 
    $id = (int)$id[0]; 
    if(!isset($arr[$id])) { 
     $arr[$id] = array(); 
    } 

    //Then we iterate through all nodes and store <report> in $arr 
    foreach($node as $report) { 
     $arr[$id][] = (string)$report; 
    } 
} 

echo "<pre>"; 
print_r($arr); 
echo "</pre>"; 

但是,这是我得到的输出:

Array 
(
    [1] => Array 
     (
     ) 

    [10] => Array 
     (
     ) 

...它继续重复通过标签的所有属性,但从不用任何信息填充阵列。

如果有人能帮助告诉我我错过了什么,我将非常感激。我觉得我对于看起来应该比较简单的事情感到失落了。

谢谢!

+0

以通用的方式执行此操作很困难,但难以从特定的XML生成特定的数组结构。迭代'emp'元素,读取特定值并生成目标数组结构。 – ThW

+0

我重写了代码,但我有一些问题需要将标记信息存储为我需要的信息。如果您有任何见解,我将不胜感激! – Drew

回答

1

你非常接近。该代码不起作用,因为第二个for循环。外层循环将遍历所有的report元素。所以,node是一个report元素。当你尝试遍历report的孩子时,那里什么也没有。

相反的第二(内)循环,只要做到这一点:

$arr[$id][] = (string)$node; 

当我做到了,我得到了以下结果:

<pre> 
Array 
(
    [1] => Array 
     (
      [0] => 07-14-2015_DPLOH_SalesID_1.pdf 
      [1] => 07-17-2015_DPLOH_SalesID_1.pdf 
      [2] => 07-14-2015_DTE_SalesID_1.pdf 
      [3] => 07-14-2015_IDT_SalesID_1.pdf 
      [4] => 07-14-2015_Kratos_SalesID_1.pdf 
      [5] => 07-14-2015_Spark_SalesID_1.pdf 
     ) 
    ) 
0

我更新你的脚本稍有不同的工作:

$emp = new SimpleXMLElement($xmlStr); 

$id = intval($emp['salesid']); 
$arr = array(
    $id   => array(), 
); 

$lst = $emp->xpath('/emp/report'); 

while (list(, $text) = each($lst)) 
{ 
    $arr[$id][] = (string) $text; 
} 

echo "<pre>"; 
print_r($arr); 
echo "</pre>"; 

干杯