-1

I am creating a webservice that accepts an XML document and all I have to do is send back a true or false. My questions is how do I validate the XML I receive and verify there are values for every node.

For example this would validate:

<ItemUpdate>
<ItemNmbr>1234</ItemNmbr>
<ItemDesc>Part Number 1 - More info goes here</ItemDesc>
<ItemPrice>8.25</ItemPrice>
<Model>TC12B</Model>
</ItemUpdate>

But this data would not

<ItemUpdate>
<ItemNmbr></ItemNmbr>
<ItemDesc>Part Number 1 - More info goes here</ItemDesc>
<ItemPrice></ItemPrice>
<Model>TC12B</Model>
</ItemUpdate>

Below is how I am handling the data so far. I am open to recomendations if there is anything I am missing:

<?PHP

if ( $_SERVER['REQUEST_METHOD'] === 'POST' ){ 

    $dataPOST = trim(file_get_contents('php://input'));
    $xmlData = simplexml_load_string($dataPOST);

    //VALIDATE $xmlData;

      if ($xmlData){
          echo true;
         }else{
          echo false;
         }

}

?>
Denoteone
  • 4,043
  • 21
  • 96
  • 150

2 Answers2

3

Define a XSD schema for it, and just call DOMDocument::schemaValidate after that. Setting up that schema first can be a bit of work, but it usually pays in the long run.

Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • Can the schema be part of the current script? Or does it have to be in another file? Thanks for the information. +1 – Denoteone Oct 29 '13 at 08:17
  • 1
    If you want to use it as a string embedded in your file, you can use [`DOMDocument::schemaValidateSource`](http://www.php.net/manual/en/domdocument.schemavalidatesource.php). I would however find it more convenient to save that .xsd schema separately so other future code may easily use it. – Wrikken Oct 29 '13 at 08:55
1

You have to load your xml and iterate through each node to check if it is blank:

    $doc = new DOMDocument();

    /* you can use your variable containing response from post here instead of 
     * hard coded string
     */

    $doc->loadXML('<ItemUpdate><ItemNmbr>1234</ItemNmbr><ItemDesc>Part Number 1 - More info goes here</ItemDesc><ItemPrice>8.25</ItemPrice><Model>TC12B</Model></ItemUpdate>');

    $nodeBlank = false;

    $x = $doc->documentElement;
    foreach ($x->childNodes AS $item){
        if(trim($item->nodeValue) == ''){
            $nodeBlank = true;
        }
    }

    if($nodeBlank){
        echo 'false';
    }else{
        echo 'true';
    }