Solved

Retieving XML data

Posted on 2009-07-04
8
218 Views
Last Modified: 2013-12-13
I'm using DomDocument to retrieve data from an XML file, my issue that the XML may not have all the data I'm requesting and consequently I'm getting errors along the lines of... Trying to get property of non-object.
I've tried a few workarounds like if isset and if($data=$doc->getElementsByTagName("pcap") but neither seem to be working. I'm not a complete idiot, what am I missing?
Thank is advance for any assistance or suggestions.
0
Comment
Question by:worldofwires
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24777301
>> Trying to get property of non-object.

This would happen when you try to read a property from something that is not an object. For example:

$a=0;
echo $a->b;

Could you post your code and some sample xml?
0
 

Author Comment

by:worldofwires
ID: 24777335
Hi, thanks for quick response.

I've included a snippet of the code I'm using and underneath the if statement is an example of what I've been trying to get around the issue. There is a sample xml file attached too, so if the car element for instance doesn't exisit, it would generate the error. I hope this makes sense.

if(file_exists('data/records/xml/'.$fn.'.xml')) {
  $doc = new DOMDocument();
  $doc->load('data/records/xml/'.$fn.'.xml');
 
  $data=$doc->getElementsByTagName("name");
  $arr['name']=array($data->item(0)->getAttribute("last"), $data->item(0)->getAttribute("first"));
 
  $data=$doc->getElementsByTagName("car");
  $arr['car']=$data->item(0)->nodeValue;
}
 
if($data=$doc->getElementsByTagName("car")) $arr['car']=$data->item(0)->nodeValue; else $arr['car']=0;

Open in new window

sample.xml.txt
0
 
LVL 39

Expert Comment

by:Roger Baklund
ID: 24777363
getElementsByTagName() returns a DOMNodeList, this object has a "length" property. Check if this is non-zero before trying to fetch anything from it.
if(file_exists('data/records/xml/'.$fn.'.xml')) {
  $doc = new DOMDocument();
  $doc->load('data/records/xml/'.$fn.'.xml');
 
  $data=$doc->getElementsByTagName("name");
  if($data->length)
    $arr['name']=array($data->item(0)->getAttribute("last"), $data->item(0)->getAttribute("first"));
  else 
    $arr['name']=false;
 
  $data=$doc->getElementsByTagName("car");
  if($data->length)
    $arr['car']=$data->item(0)->nodeValue;
  else 
    $arr['car']=0;
}
 
# The problem with this:
if($data=$doc->getElementsByTagName("car")) 
  $arr['car']=$data->item(0)->nodeValue; else $arr['car']=0;
# ...is that getElementsByTagName() allways returns an object (DOMNodeList), even if no nodes was found.
# Thus, the if-statement is allways true.

Open in new window

0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:worldofwires
ID: 24778102
Thanks cxr,

Just to check I've got this, so in my code I can do $data=$doc->getElementsByTagName("car"); And then do an IF statement saying if $data!=0 then use nodeValue, else it's 0?

It seems to work, I'm just clarifying I understand what's going on. Also, in your opinion, is there a problem with constantly reusing the $data value for each getElementByTagName?

Much appreciated.
0
 
LVL 39

Accepted Solution

by:
Roger Baklund earned 75 total points
ID: 24778182
>> if $data!=0 then use nodeValue

No, the name of the property is $data->length. You can write just:

if($data->length)

This will be true if length > 0, false if it is 0. In effect it is the same as

if($data->length!=0)

>> is there a problem with constantly reusing the $data value for each getElementByTagName?

No, I don't see any problem with that. On the contrary, it reduces memory consumption.
0
 
LVL 110

Assisted Solution

by:Ray Paseur
Ray Paseur earned 50 total points
ID: 24778186
This shows how to use SimpleXML to achieve similar results.  I like SimpleXML because I am an inherently simple person ;-)

HTH, ~Ray
<?php // RAY_xml_example_24.php
error_reporting(E_ALL);
echo "<pre>\n"; // READABILITY
 
 
 
// TEST DATA FROM THE ORIGINAL POST USING HEREDOC SYNTAX
// MAN PAGE http://www.tuxradar.com/practicalphp/2/6/3
$xml = <<<MYXML
<?xml version="1.0"?>
<record>
  <effective>2009-01-26</effective>
  <generated_date>2009-01-05 11:48:06</generated_date>
  <generated_by>13</generated_by>
  <reason code="OFFERV2" title="Offer to Employee v2" id="10"/>
  <parent code="LEGAL AMEA" title="Chief Counsel, AMEA Region" id="25"/>
  <name first="Mickey" last="Mouse"/>
  <hypo allowance="6035" deduction="2531.25" total="3503.75" code="350L"/>
  <car>1</car>
</record>
MYXML;
 
 
 
// MAKE AN OBJECT
$obj = SimpleXML_Load_String($xml);
var_dump($obj);
 
// ACCESS THE DATA TO SIMULATE SOME PROCESSING ROUTINES
$arr = array();
 
// GET THE NAME FROM THE ATTRIBUTES OF AN XML TAG
$arr["name"] = $obj->name["first"] . ' ' . $obj->name["last"];
// GET A FIELD THAT DOES NOT EXIST
$arr["foo"]  = (bool)   $obj->foo;
// GET AN ELEMENT FROM WITHIN THE XML TAG
$arr["car"]  = (string) $obj->car;
 
// VISUALIZE THE DATA
var_dump($arr);

Open in new window

0
 

Author Comment

by:worldofwires
ID: 24778211
Thanks both,

I've used the SimpleXML on another XML function but got a little lost when using attributes. I like to keep things simple. :) I may rewrite but in teh meantime, xcr has solved my error generating problem.

Excellent, thaks guys. This site rocks.
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 24778216
Thanks for the points.  The rule of attributes is that they are array indexes.  See line 33 of the post above for the way to isolate those.  Best regards, ~Ray
0

Featured Post

Secure Your Active Directory - April 20, 2017

Active Directory plays a critical role in your company’s IT infrastructure and keeping it secure in today’s hacker-infested world is a must.
Microsoft published 300+ pages of guidance, but who has the time, money, and resources to implement? Register now to find an easier way.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In this article you will learn how to create a free basic website on Bitbucket, a git service provider. Polymer creates dynamic HTML components, which allow more flexibility than static HTML. This tutorial uses Ubuntu Linux but can also be done on W…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

756 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question