Solved

Retieving XML data

Posted on 2009-07-04
8
217 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
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 

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

Free Tool: SSL Checker

Scans your site and returns information about your SSL implementation and certificate. Helpful for debugging and validating your SSL configuration.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Number of reviews not counting correctly 2 22
Test if unique ID is in log file 5 21
Link failure 16 32
Ajax and PHP 4 30
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Generating table dynamically is the most common issue faced by php developers.... So it seems there is a need of an article that explains the basic concept of generating tables dynamically. It just requires a basic knowledge of html and little maths…
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 create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …

856 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