【问题标题】:Search a xml element by an attribute in php通过php中的属性搜索xml元素
【发布时间】:2013-04-24 16:37:08
【问题描述】:

我认为问题是重复的,但我对以前的答案不满意。

我有一个 XML 文件

<?xml version="1.0" encoding="UTF-8"?> <forms xml:id="cust_type">
     <form>
        <element id="cust_type" type="dropdown" name="cust_type" desc="Customer Type*"  value="" div_attr="select_long" 
 class="required select" validate="required"></element>
<element type="text" name="form_no" desc="Form No"  div_attr="txt_short" value="" class="number" validate="numeric"></element>
</form> 
</forms>

我只想获取 id="cust_type" 或 name="cust_type" 的元素。 但我没听懂。

请建议我使用 SimpleXML 或 DOMDocument 的代码。

【问题讨论】:

  • php.net/domxpath - 请展示你的尝试
  • 我尝试了以下 $file = file_get_contents('URL_TO_FILE'); $doc = 新的 DOMDocument(); $doc->loadXML($file); print_r($doc->getElementById('cust_type'));但输出为 DOMElement Object ( )

标签: php xml simplexml domdocument


【解决方案1】:

使用simplexmlxpath

$xml = simplexml_load_string($x); // assume XML in $x
$elements = $xml->xpath("//element[@id='cust_type' or @name='cust_type']");
foreach ($elements as $element) echo $element['name'] . "<br />";

查看工作演示:http://codepad.viper-7.com/EzmGWJ

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2016-10-03
    • 2011-10-31
    • 2019-02-08
    • 1970-01-01
    相关资源
    最近更新 更多