Solved

Retieving XML data

Posted on 2009-07-04
8
216 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
  • 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
ScreenConnect 6.0 Free Trial

Want empowering updates? You're in the right place! Discover new features in ScreenConnect 6.0, based on partner feedback, to keep you business operating smoothly and optimally (the way it should be). Explore all of the extras and enhancements for yourself!

 

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 109

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 109

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

Best Practices: Disaster Recovery Testing

Besides backup, any IT division should have a disaster recovery plan. You will find a few tips below relating to the development of such a plan and to what issues one should pay special attention in the course of backup planning.

Question has a verified solution.

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

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
The viewer will learn how to count occurrences of each item in an array.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

803 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