从XML内容中使用PHP获取元素

huangapple go评论76阅读模式
英文:

Get elements from a XML content by PHP

问题

我正在尝试从这个XML内容中获取元素,但返回为空:

<results>
  <error>
    <string>i</string>
    <description>Make I uppercase</description>
    <precontext></precontext>
    <suggestions>
        <option>I</option>
    </suggestions>
    <type>grammar</type>    
  </error>
</results>

这是提取语法类型元素的代码:

$dom = new DOMDocument();
$dom->loadXml($output);
$params = $dom->getElementsByTagName('error'); // 查找部分
$k=0;
foreach ($params as $param) // 逐个处理每个部分
{
    if($param->type == "grammar"){
        echo $param->description;
    }else{
        echo "other type";
    }
}

问题是脚本返回为空。

英文:

I am trying to get elements from this XML content but returns empty:

&lt;results&gt;
  &lt;error&gt;
    &lt;string&gt;i&lt;/string&gt;
    &lt;description&gt;Make I uppercase&lt;/description&gt;
    &lt;precontext&gt;&lt;/precontext&gt;
    &lt;suggestions&gt;
        &lt;option&gt;I&lt;/option&gt;
    &lt;/suggestions&gt;
    &lt;type&gt;grammar&lt;/type&gt;    
  &lt;/error&gt;
&lt;/results&gt;

And this is my code to extract element type of grammar :

$dom = new DOMDocument();
$dom-&gt;loadXml($output);
$params = $dom-&gt;getElementsByTagName(&#39;error&#39;); // Find Sections
$k=0;
foreach ($params as $param) //go to each section 1 by 1
{
    if($param-&gt;type == &quot;grammar&quot;){
        echo $param-&gt;description;
    }else{
        echo &quot;other type&quot;;
    }

Problem is the script returns empty.

答案1

得分: 1

你可以使用 simplexml_load_string()

$output = '<results>
          <error>
            <string>i</string>
            <description>将I大写</description>
            <precontext></precontext>
            <suggestions>
                <option>I</option>
            </suggestions>
            <type>语法</type>    
          </error>
        </results>';

$xml = simplexml_load_string($output);

foreach($xml->error as $item)
{
    //echo (string)$item->type;
    
    if($item->type == "语法"){

    echo $item->description;

    }else{
     echo "其他类型";

    }
}
英文:

you can use simplexml_load_string()

 $output = &#39;&lt;results&gt;
      &lt;error&gt;
        &lt;string&gt;i&lt;/string&gt;
        &lt;description&gt;Make I uppercase&lt;/description&gt;
        &lt;precontext&gt;&lt;/precontext&gt;
        &lt;suggestions&gt;
            &lt;option&gt;I&lt;/option&gt;
        &lt;/suggestions&gt;
        &lt;type&gt;grammar&lt;/type&gt;    
      &lt;/error&gt;
    &lt;/results&gt;&#39;;
    
    
    $xml = simplexml_load_string($output);
    
    foreach($xml-&gt;error as $item)
    {
        //echo (string)$item-&gt;type;
        
        if($item-&gt;type == &quot;grammar&quot;){
    
        echo $item-&gt;description;
    
        }else{
         echo &quot;other type&quot;;
    
        }
    }

答案2

得分: 1

你显然没有配置PHP来报告错误,因为你的代码触发了以下错误:

注意:未定义属性:DOMElement::$type

你需要以与获取<error>相同的方式获取<type>,使用DOM方法,例如getElementsByTagName()。对于节点的值也是一样的:

if ($param->getElementsByTagName('type')->length && $param->getElementsByTagName('type')[0]->nodeValue === 'grammar') {
    // 随时可以添加其他检查:
    echo $param->getElementsByTagName('description')[0]->nodeValue;
} else {
    echo "其他类型";
}

演示

英文:

You apparently haven't configured PHP to report errors because your code triggers:

> Notice: Undefined property: DOMElement::$type

You need to grab &lt;type&gt; the same way you grab &lt;error&gt;, using DOM methods like e.g. getElementsByTagName(). Same for node value:

if ($param-&gt;getElementsByTagName(&#39;type&#39;)-&gt;length &amp;&amp; $param-&gt;getElementsByTagName(&#39;type&#39;)[0]-&gt;nodeValue === &#39;grammar&#39;) {
    // Feel free to add additional checks here:
    echo $param-&gt;getElementsByTagName(&#39;description&#39;)[0]-&gt;nodeValue;
}else{
    echo &quot;other type&quot;;
}

Demo

答案3

得分: 1

I think is this what you want.

<?php

$output = '<results>
  <error>
    <string>i</string>
    <description>Make I uppercase</description>
    <precontext></precontext>
    <suggestions>
        <option>I</option>
    </suggestions>
    <type>grammar</type>
  </error>
</results>';

$dom = new DOMDocument();
$dom->loadXml($output);
$params = $dom->getElementsByTagName('error'); // Find Sections
$k = 0;

foreach ($params as $param) //go to each section 1 by 1
{
    $string = $param->getElementsByTagName("string")->item(0)->nodeValue;
    $description = $param->getElementsByTagName("description")->item(0)->nodeValue;
    $option = $param->getElementsByTagName("option")->item(0)->nodeValue;
    $type = $param->getElementsByTagName("type")->item(0)->nodeValue;
    echo $type;
    if ($type == "grammar") {
        echo $description;
    } else {
        echo "other type";
    }
}
?>
英文:

I think is this what you want.

       &lt;?php
    
    $output  = &#39;&lt;results&gt;
      &lt;error&gt;
        &lt;string&gt;i&lt;/string&gt;
        &lt;description&gt;Make I uppercase&lt;/description&gt;
        &lt;precontext&gt;&lt;/precontext&gt;
        &lt;suggestions&gt;
            &lt;option&gt;I&lt;/option&gt;
        &lt;/suggestions&gt;
        &lt;type&gt;grammar&lt;/type&gt;    
      &lt;/error&gt;
    &lt;/results&gt;&#39;;
    
    $dom = new DOMDocument();
    $dom-&gt;loadXml($output);
    $params = $dom-&gt;getElementsByTagName(&#39;error&#39;); // Find Sections
    $k=0;
    
    
    foreach ($params as $param) //go to each section 1 by 1
    {
        $string = $param-&gt;getElementsByTagName( &quot;string&quot; )-&gt;item(0)-&gt;nodeValue;
        $description = $param-&gt;getElementsByTagName( &quot;description&quot; )-&gt;item(0)-&gt;nodeValue;
        $option = $param-&gt;getElementsByTagName( &quot;option&quot; )-&gt;item(0)-&gt;nodeValue;
        $type = $param-&gt;getElementsByTagName( &quot;type&quot; )-&gt;item(0)-&gt;nodeValue;
        echo $type;
        if($type == &quot;grammar&quot;){
            echo $description ;
        }else{
            echo &quot;other type&quot;;
        }
    }
?&gt;

答案4

得分: 1

你正在混合使用DOM和SimpleXML。这是可能的,但你需要使用simplexml_import_dom()将DOM元素节点转换为SimpleXML实例。

或者你可以使用XPath。getElementsByTagName()是一种低级DOM方法。使用XPath表达式可以更具体地访问,而且需要更少的代码。

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

foreach ($xpath->evaluate('//error') as $error) {
    var_dump(
        [
            'type' => $xpath->evaluate('string(type)', $error),
            'description' => $xpath->evaluate('string(description)', $error)
        ]
    );
}

输出:

array(2) {
  ["type"]=>
  string(7) "grammar"
  ["description"]=>
  string(16) "Make I uppercase"
}

XPath表达式还允许使用条件,例如你可以使用//error[@type = "grammar"]来获取所有语法错误。

英文:

You're mixing DOM with SimpleXML. This is possible, but you would need to convert the DOM element node into a SimpleXML instance with simplexml_import_dom().

Or you use Xpath. getElementsByTagName() is a low level DOM method. Using Xpath expressions allows for more specific access with a lot less code.

$document = new DOMDocument();
$document-&gt;loadXML($xml);
$xpath = new DOMXpath($document);

foreach ($xpath-&gt;evaluate(&#39;//error&#39;) as $error) {
    var_dump(
        [
            &#39;type&#39; =&gt; $xpath-&gt;evaluate(&#39;string(type)&#39;, $error),
            &#39;description&#39; =&gt; $xpath-&gt;evaluate(&#39;string(description)&#39;, $error)
        ]
    );
}

Output:

array(2) {
  [&quot;type&quot;]=&gt;
  string(7) &quot;grammar&quot;
  [&quot;description&quot;]=&gt;
  string(16) &quot;Make I uppercase&quot;
}

Xpath expressions allow for conditions as well, for example you could fetch all grammar errors using //error[@type = &quot;grammar&quot;].

huangapple
  • 本文由 发表于 2020年1月3日 15:16:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/59574595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定