Php: Check If Xml Node Exists with Attribute

Check if xml node exists in PHP

Sounds like a simple isset() solves this problem.

<?php
$s = new SimpleXMLElement('<foo version="1">
<weather section="0" />
<problem_cause data="" />
</foo>');
// var_dump($s) produces the same output as in the question, except for the object id numbers.
echo isset($s->problem_cause) ? '+' : '-';

$s = new SimpleXMLElement('<foo version="1">
<weather section="0" />
</foo>');
echo isset($s->problem_cause) ? '+' : '-';

prints +- without any error/warning message.

PHP: Check if XML node exists with attribute

I'd suggest the following (PHP using ext/simplexml and XPath):

$name = 'Shiny Red';
$xml = simplexml_load_string('<?xml version="1.0" encoding="UTF-8"?>
<targets>
<showcases>
<building name="Big Blue" />
<building name="Shiny Red" />
<building name="Mellow Yellow" />
</showcases>
</targets>');
$nodes = $xml->xpath(sprintf('/targets/showcases/building[@name="%s"]', $name);
if (!empty($nodes)) {
printf('At least one building named "%s" found', $name);
} else {
printf('No building named "%s" found', $name);
}

PHP check if XML node exists before saving to variable?

You need to use XPath. If you're using DOMDocument, this is done via DOMXpath.

Your current approach uses chaining, and the problem with chaining is it breaks down if a particular juncture of it doesn't return what the following method relies on. Hence your error.

Instead, check the whole path from the start:

$domxp = new DOMXpath($dom_object);
$node = $domxp->query('/Categories[1]/Category[1]/Code[1]');
if (count($node)) {
//found - do something
}

PHP check if element exists in XML

SimpleXML implements different interfaces for the properties. If you use it like a string it will return the content of the first matching element. If you use it like a list, you can iterate all matching elements.

$products = new SimpleXmlElement($xml);

foreach ($products->product as $product) {
foreach ($product->properties->prop as $property) {
var_dump((string)$property->property);
}
}

Output:

string(5) "Farbe"
string(13) "Geeignet für"
string(10) "Verpackung"
string(12) "Gesamturteil"
string(8) "Garantie"
string(16) "Art der Garantie"

I would suggest defining an array of default values for each propid that you like to read. The propid should be more stable then the title and is not language specific. In the inner loop you validate that the id of the current exists in that array and assign the value or valueid.

foreach ($products->product as $product) {
// default values for each product property by `prodid`
$row = [
'25' => '',
'41' => ''
];
foreach ($product->properties->prop as $property) {
$id = (string)$property->propid;
if (array_key_exists($id, $row)) {
$row[$id] = (string)$property->value;
}
}
var_dump($row);
}

Output:

array(2) {
[25]=>
string(5) "Weiß"
[41]=>
string(6) "Unisex"
}

This way the result will always have the same count and order of elements.

Fetching specific elements if they exists

To fetch a specific property use Xpath. For example to fetch the property with the propid 25:

foreach ($products->product as $product) {
$colors = $product->xpath('properties/prop[propid = 25]');
if (count($colors) > 0) {
var_dump((string)$colors[0]->property);
}
}

SimpleXmlElement::xpath() will always return an array of SimpleXmlElement objects. Validate the element count to check if the Xpath expression found a node.

DOM even allows you to fetch the scalar values directly. It will return a empty value if no node matches. The result of DOMXpath::evaluate() depends on the expression. Location paths return a DOMNodeList that is traversable with foreach. A expression that results in a scalar will return the scalar value.

$document = new DOMDocument();
$document->loadXml($xml);
$xpath = new DOMXpath($document);

foreach ($xpath->evaluate('/products/product') as $product) {
$hasColor = $xpath->evaluate('count(properties/prop[propid = 25]) > 0', $product);
if ($hasColor) {
var_dump('Color:', $xpath->evaluate('string(properties/prop[propid = 25]/valueid)', $product));
}
}

Output:

string(6) "Color:"
string(3) "208"

How to check if SimpleXMLElement Object's attribute exist - PHP

You can use !empty()

if(!empty($somevariable->Userinfo->attributes())){
// do stuff here
}

Sample output:- https://3v4l.org/R32Bv

Or you can use isset() too

if(isset($somevariable->Userinfo)){
// do stuff here
}

PHP: How to check if a node exists and if not using xpath?

I'm not sure of the exact syntax, but you might try counting the number of nodes in the target node set and seeing if it's greater than zero.

For example, count(//Reach) > 0

Another option appears to be to use boolean(//Reach)

See xpath find if node exists



Related Topics



Leave a reply



Submit