2015-04-07 108 views
1

我正面临一个Xml问题。可能是一些愚蠢的,但我不能看到它... ...Php xml,用xml对象代替正在使用的节点

这是我在开始创建XML:

<combinations nodeType="combination" api="combinations"> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/1"> 
     <id><![CDATA[1]]></id> 
    </combination> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/2"> 
     <id><![CDATA[2]]></id> 
    </combination> 
</combinations> 

因此,对于每一个节点,我做的API调用,然后我想,以取代由节点返回的值,这样的:

$c_index = 0; 
foreach($combinations->combination as $c){ 
    $new = apiCall($c->id); //load the new content 
    $combinations->combination[$c_index] = $new; 
    $c_index++; 
} 

如果我转储$新进的foreach,我得到了一个simplexmlobject这是很好的,但如果我转储$ combinations->组合[$ X],我已经得到了很大的字符串空白...

我想获得:

<combinations nodeType="combination" api="combinations"> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/1"> 
     <my new tree> 
      .... 
     </my new tree> 
    </combination> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/2"> 
     <my new tree> 
      .... 
     </my new tree> 
    </combination> 
</combinations> 

我必须缺少一些东西,但是什么......?这就是问题...

感谢您的帮助!

回答

0

您可以通过使用所谓的的SimpleXMLElement自参考的改变foreach迭代的当前元素$c。通过SimpleXMLElement的神奇性质,数字访问或数字0(零)的属性访问的条目表示元素本身。这可以用来更改的元素值例如:

foreach ($combinations->combination as $c) { 
    $new = apiCall($c->id); //load the new content 
    $c[0] = $new; 
} 

重要的部分是$c[0]这里。您也可以使用数字编写$c->{0}以进行媒体资源访问。示例输出(可以API调用返回 “apiCall($paramter)” 作为字符串):

<combinations nodeType="combination" api="combinations"> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/1">apiCall('1')</combination> 
    <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/2">apiCall('2')</combination> 
</combinations> 

在完整示例:

$buffer = <<<XML 
<root xmlns:xlink="ns:1"> 
    <combinations nodeType="combination" api="combinations"> 
     <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/1"> 
      <id><![CDATA[1]]></id> 
     </combination> 
     <combination xlink:href="http://localhost:8888/vmv/ps/api/combinations/2"> 
      <id><![CDATA[2]]></id> 
     </combination> 
    </combinations> 
</root> 
XML; 


function apiCall($string) 
{ 
    return sprintf('apiCall(%s)', var_export((string)$string, true)); 
} 

$xml = simplexml_load_string($buffer); 

$combinations = $xml->combinations; 

foreach ($combinations->combination as $c) { 
    $new = apiCall($c->id); //load the new content 
    $c[0] = $new; 
} 

$combinations->asXML('php://output');