PHP Work with Missing XML Data

If I have three datasets, say:

<note><from>Me</from><to>someone</to><message>hello</message></note>

<note><from>Me</from><to></to><message>Need milk & eggs</message></note>

<note><from>Me</from><message>Need milk & eggs</message></note>

and I use simplexml, is there a simple xml way to check that there is a blank / missing tag automatically?

I would like the result to be:

FROM    TO     MESSAGE
Me    someone    hello
Me    NULL    Need milk & eggs
Me    NULL    Need milk & eggs

Now I am doing this manually, and I quickly realized that long xml files would take a very long time.

My current code example:

$xml = simplexml_load_string($string);
if ($xml->from != "") {$out .= $xml->from."\t"} else {$out .= "NULL\t";}
//repeat for all children, checking by name

Sometimes the order is different from the other, maybe xml with:

<note><message>pick up cd</message><from>me</from></note>

therefore iterating through children and checking by index do not work.

The actual xml files I'm working with are thousands of lines each, so I obviously can't just encode in each tag.

+3
source share
2 answers

DOMDocument. , <note> , XML . .

XML, HTML (&amp;).

<?php
    libxml_use_internal_errors(true);
    $xml = <<<XML
<notes>
<note><from>Me</from><to>someone</to><message>hello</message></note>
<note><from>Me</from><to></to><message>Need milk &amp; eggs</message></note>
<note><from>Me</from><message>Need milk &amp; eggs</message></note>
<note><message>pick up cd</message><from>me</from></note>
</notes>
XML;

    function getNotes($nodelist) {
        $notes = array();

        foreach ($nodelist as $node) {
            $noteParts = array();

            foreach ($node->childNodes as $child) {
                $noteParts[$child->tagName] = $child->nodeValue;
            }

            $notes[] = $noteParts;
        }

        return $notes;
    }

    $dom = new DOMDocument();
    $dom->recover = true;
    $dom->loadXML($xml);
    $xpath = new DOMXPath($dom);
    $nodelist = $xpath->query("//note");
    $notes = getNotes($nodelist);

    print_r($notes);
?>

: $noteParts = array(); $noteParts = array('from' => null, 'to' => null, 'message' => null);, .

+1

, DTD ( ), XML , , , ..

DTD XML, - .

, PHP simplexml DTD, DomDocument , .

excersise , , DTD . , .

+2

All Articles