1

I've an XML ( $fileXML ) like:

<FatturaElettronicaHeader>
   <CedentePrestatore>
      <DatiAnagrafici>
        <Anagrafica>
          <Denominazione>MY STORE SRL</Denominazione>
          <Cognome>Rossi</Cognome>
        </Anagrafica>
      </DatiAnagrafici>
   </CedentePrestatore>
</FatturaElettronicaHeader>

I use this function to retrieve some values:

$xml = new DOMDocument();
$xml->loadXML($fileXML);
$xpath = new DOMXPath($xml);            
$nodes = $xpath->query('//CedentePrestatore/DatiAnagrafici');
foreach ($nodes as $nodelist) {

  $denominazione = $xpath->query( 'Anagrafica/Denominazione', $nodelist)->item(0)->nodeValue;
  $cognome = $xpath->query( 'Anagrafica/Cognome', $nodelist)->item(0)->nodeValue;

}

It work great. But node Cognome is optional in the XML, so sometimes it doesn't exist, like:

<FatturaElettronicaHeader>
   <CedentePrestatore>
      <DatiAnagrafici>
        <Anagrafica>
          <Denominazione>MY SHOP2 SRL</Denominazione>
        </Anagrafica>
      </DatiAnagrafici>
   </CedentePrestatore>
</FatturaElettronicaHeader>

Then my script get error: Trying to get property of non-object

How can I modify my code to assign at variable $cognome node value if exist, empty string "" in other cases?

3
  • Which of these lines shows the problem? Why not check whether an object is returned by any of these method calls or not? Commented Feb 6, 2019 at 9:42
  • $cognome = $xpath->query( 'Anagrafica/Cognome', $nodelist)->item(0)->nodeValue; when use the second XML example, where Cognome is not present Commented Feb 6, 2019 at 9:43
  • And why not check whether $xpath->query( 'Anagrafica/Cognome', $nodelist)->item(0) is an object or not? Commented Feb 6, 2019 at 9:44

1 Answer 1

4

Chech that xpath returns any node

$cognome = $xpath->query( 'Anagrafica/Cognome', $nodelist);
$cognome = $cognome->length ? $cognome->item(0)->nodeValue : '';
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.