2

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 Answer 1

2

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..

Sign up to request clarification or add additional context in comments.

1 Comment

Awesome :) Definitely going to put this to practice and learn different ways to use this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.