我有一个xml文档,我正在获取"value"的内容以存储为PHP变量以进行检查和过滤。
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<Attributes>
<EventAttribute>
<Name>Event Type</Name>
<Value>Cinema</Value>
</EventAttribute>
<EventAttribute>
<Name>Venue</Name>
<Value>Bonanza</Value>
</EventAttribute>
</Attributes>
</Event>
我使用了以下PHP代码:
<?php
$xml=simplexml_load_file("event.xml");
$typeevent = $xml->Attributes->EventAttribute[0]->Value;////should be Cinema
$typevenue = $xml->Attributes->EventAttribute[1]->Value;//should be Bonanza
echo "<p>" . $typeevent . "</p>";
echo "<p>" . $typevenue . "</p>";
?>
这给了我以下工作正常的输出:
电影院
金矿
问题:
我无法控制的系统可以添加新节点,因此会弄乱排序,因此 EventAttribute[1] 现在可以引用完全不同的内容。我做了一些研究,但我只是无法理解它。理想情况下,我想要这样的东西:
$typeevent = $xml->Attributes->EventAttribute-> -- 其中 'name' = 'EventType' 给我"值"。
$typevenue = $xml->属性->事件属性-> -- 其中"名称"="场地"给我"值"。
希望这有意义吗?
如果要使用DOMDocument
则可以使用DOMXPath
并使用相当简单的语法来定位所需的节点,而不管XML源中节点的顺序或数量如何。
一个非常有用的 XPath 参考可以在这里找到
<?php
$xml='<?xml version="1.0" encoding="UTF-8"?>
<Event>
<Attributes>
<EventAttribute>
<Name>Event Type</Name>
<Value>Cinema</Value>
</EventAttribute>
<EventAttribute>
<Name>Venue</Name>
<Value>Bonanza</Value>
</EventAttribute>
</Attributes>
</Event>';
$dom=new DOMDocument;
$dom->loadXML( $xml );
$xp=new DOMXPath( $dom );
/* helper functions */
function getnode( $xp, $ref, $query ){
return $xp->query( $query, $ref )->item(0) ?: false;
}
function getvalue($node){
return $node->nodeValue;
}
$type=getnode( $xp, null, '//EventAttribute/Name[ text()="Event Type" ]' );
$value=getnode( $xp, $type->parentNode, 'Value' );
printf("%s -> %s<br />n", getvalue( $type ), getvalue( $value ) );
$type=getnode( $xp, null, '//EventAttribute/Name[ text()="Venue" ]' );
$value=getnode( $xp, $type->parentNode, 'Value' );
printf("%s -> %s<br />n", getvalue( $type ), getvalue( $value ) );
?>
这将输出:
Event Type -> Cinema
Venue -> Bonanza
我不熟悉SimpleXML
及其相关方法,因此很可能与此处使用的DOMXPath
类等效,我不知道。
如果您不希望返回存储在Name
元素本身中的值,而只是获取值,则可以使用同级选择器专门针对该节点
$value=getvalue( getnode( $xp, null, '//EventAttribute/Name[ text()="Event Type" ]/following-sibling::Value' ) );
echo $value; // outputs Cinema
访问该样式的成员,则需要生成一个关联数组,键为EventAttribute->Name
:
<?php
$xmlstring = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<Event>
<Attributes>
<EventAttribute>
<Name>Event Type</Name>
<Value>Cinema</Value>
</EventAttribute>
<EventAttribute>
<Name>Venue</Name>
<Value>Bonanza</Value>
</EventAttribute>
</Attributes>
</Event>
XML;
$event = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$event_attributes = [];
foreach ($event->Attributes->EventAttribute as $event_attribute) {
// Note, explicitly casting values to strings.
$event_attributes[(string)$event_attribute->Name] = (string)$event_attribute->Value;
}
echo $event_attributes['Event Type'] . PHP_EOL;
echo $event_attributes['Venue'] . PHP_EOL;
print_r($event_attributes);
输出:
Cinema
Bonanza
Array
(
[Event Type] => Cinema
[Venue] => Bonanza
)