Solved

Retieving XML data

Posted on 2009-07-04
8
215 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
Comment Utility
>> 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
Comment Utility
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
Comment Utility
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
 

Author Comment

by:worldofwires
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 39

Accepted Solution

by:
Roger Baklund earned 75 total points
Comment Utility
>> 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 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 50 total points
Comment Utility
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
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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 Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
posting form data 3 23
Button Click 11 22
Setting Up Local Lan Web Server 1 12
writting html or javascript in PHP 8 0
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

728 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now