?
Solved

Retieving XML data

Posted on 2009-07-04
8
Medium Priority
?
221 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 

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 300 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 200 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 111

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

On Demand Webinar: Networking for the Cloud Era

Ready to improve network connectivity? Watch this webinar to learn how SD-WANs and a one-click instant connect tool can boost provisions, deployment, and management of your cloud connection.

Question has a verified solution.

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

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
This article discusses four methods for overlaying images in a container on a web page
The purpose of this video is to demonstrate how to set up the WordPress backend so that each page automatically generates a Mailchimp signup form in the sidebar. This will be demonstrated using a Windows 8 PC. Tools Used are Photoshop, Awesome…
The viewer will learn how to count occurrences of each item in an array.
Suggested Courses

752 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