f



How to find non-existing nodes or nodes with no text

Ok, this must be simple but the more i search the more i don't find.
It's about SimpleXML and PHP.
How to find non-existing nodes or nodes with no text

My XML file looks a little bit like this:

i.e. 1
<discography>
   <CD>
	<title></title>
	<year>1978</year>
   </CD>
</discography>


i.e. 2:
<discography>
   <CD>
	<year>1978</year>
   </CD>
</discography>


In i.e. 1, the tag <title> is empty. How do i test for empty tags in
PHP?
In i.e. 2, the tag <title> doesn't even exist. How do i test for non-
existing tags?


This is how i get the values from XML in PHP without validation
....
//set the XML file name as a PHP string
$cd_xml = "db/discography/cd.xml";

//load the XML file
$xml = @simplexml_load_file($cd_xml) or die ("Error: The XML file
can't open.") ;
....

//no validation if empty, creates empty <h1> tags. Not good!
<h1><?php echo $xml->CD->title; ?></h1>
<h2><?php echo $xml->CD->year; ?></h2>





How to validate?
Any suggestions?

Thanks in advance
Marco
0
5/9/2008 11:01:10 PM
comp.lang.php 32646 articles. 0 followers. Post Follow

1 Replies
731 Views

Similar Articles

[PageSpeed] 52

<?php if (isset($xml->CD->title) && trim($xml->CD->title) != '') { ?>

  <h1><?php echo $xml->CD->title ?></h1>

<?php } ?>

On May 9, 7:01 pm, SM <servandomont...@gmail.com> wrote:
> Ok, this must be simple but the more i search the more i don't find.
> It's about SimpleXML and PHP.
> How to find non-existing nodes or nodes with no text
>
> My XML file looks a little bit like this:
>
> i.e. 1
> <discography>
>    <CD>
>         <title></title>
>         <year>1978</year>
>    </CD>
> </discography>
>
> i.e. 2:
> <discography>
>    <CD>
>         <year>1978</year>
>    </CD>
> </discography>
>
> In i.e. 1, the tag <title> is empty. How do i test for empty tags in
> PHP?
> In i.e. 2, the tag <title> doesn't even exist. How do i test for non-
> existing tags?
>
> This is how i get the values from XML in PHP without validation
> ...
> //set the XML file name as a PHP string
> $cd_xml = "db/discography/cd.xml";
>
> //load the XML file
> $xml = @simplexml_load_file($cd_xml) or die ("Error: The XML file
> can't open.") ;
> ...
>
> //no validation if empty, creates empty <h1> tags. Not good!
> <h1><?php echo $xml->CD->title; ?></h1>
> <h2><?php echo $xml->CD->year; ?></h2>
>
> How to validate?
> Any suggestions?
>
> Thanks in advance
> Marco

0
petersprc (357)
5/10/2008 5:01:07 AM
Reply: