0

I'm fetching some xml and convert it to csv similar to this post PHP - Fetch correct XML values if elements have similar tags per record. If I have an incorrect Date element like '0000-00-00' ... in the csv I want it to be empty ''.

This is my structure

XML Elements:

<abc:ABC>5EXZX4LPK</abc:ABC>
<abc:Date>0000-00-00</abc:Date> 
<abc:Name>I Bornheim</abc:Name>

php xpath xmlreader:

fputcsv(
  $output, 
  [
    $xpath->evaluate('string(abc:ABC)', $node),
    $xpath->evaluate('string(abc:Entity/abc:Date)', $node)        
    $xpath->evaluate('string(abc:Entity/abc:Name)', $node)
  ]
);

Output:

5EXZX4LPK,0000-00-00,"I Bornheim"  

Desired Output:

5EXZX4LPK,,"I Bornheim"  

How can I accomplish this?

1 Answer 1

1

You can check if it's a valid date by decomposing it into the year-month-day and then using checkdate()...

$date = $xpath->evaluate('string(abc:Entity/abc:Date)', $node);
$parts = explode("-", $date);
$date = (count($parts)== 3) &&
    checkdate($parts[1], $parts[2], $parts[0]) ? $date : '';

This explodes the date with - and checks there are 3 parts and that all the parts make up a valid date.

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

Comments

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.