PHP Handling Namespace with SimpleXML

守給你的承諾、 提交于 2020-01-04 05:17:19

问题


I really need help with using namespaces. How do I get the following code to work properly?

<?php
$mytv = simplexml_load_string(
'<?xml version="1.0" encoding="utf-8"?>
 <mytv>
    <mytv:channelone>
        <mytv:description>comedy that makes you laugh</mytv:description>
    </mytv:channelone>
 </mytv>'
);

foreach ($mytv as $mytv1)
{
    echo 'description: ', $mytv1->children('mytv', true)->channelone->description;
}
?>

All I'm trying to do is get the content inside the name element.


回答1:


when ever yu are using the namespaces in xml yu should define the namespaces what ever you use..! in the code what i posted you can see how you can define the namespace you are using..

you need to display the description specific to the namespace isn't it..? correct me if I'm wrong., and please post yur purpose properly so that i can understand your problem..

Use this code and see if you can get some idea..

$xml ='<mytv>
 <mytv:channelone xmlns:mytv="http://mycompany/namespaces/mytvs">
    <mytv:description >comedy that makes you laugh</mytv:description>
 </mytv:channelone>
</mytv>';

$xml = simplexml_load_string($xml);

$doc = new DOMDocument();  
$str = $xml->asXML(); 
$doc->loadXML($str); 

$bar_count = $doc->getElementsByTagName("description");

foreach ($bar_count as $node) 
{   
echo $node->nodeName." - ".$node->nodeValue."-".$node->prefix. "<br>";
}

here., the value, "$node->prefix" will be the namespace of the tag containing "description".

getElementsByTagName("description") is used to get all the elements in the xml containing description as tags...!! and then later using the "$node->prefix" you compare with the specific namespace as required for you and then print..



来源:https://stackoverflow.com/questions/8275643/php-handling-namespace-with-simplexml

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!