Getting the text portion of a node using php Simple XML

前端 未结 7 2163
臣服心动
臣服心动 2020-12-03 18:39

Given the php code:

$xml = <<
This is a link Title with some text following it.
7条回答
  •  不思量自难忘°
    2020-12-03 19:41

    There might be ways to achieve what you want using only SimpleXML, but in this case, the simplest way to do it is to use DOM. The good news is if you're already using SimpleXML, you don't have to change anything as DOM and SimpleXML are basically interchangeable:

    // either
    $articles = simplexml_load_string($xml);
    echo dom_import_simplexml($articles)->textContent;
    
    // or
    $dom = new DOMDocument;
    $dom->loadXML($xml);
    echo $dom->documentElement->textContent;
    

    Assuming your task is to iterate over each

    and get its content, your code will look like

    $articles = simplexml_load_string($xml);
    foreach ($articles->article as $article)
    {
        $articleText = dom_import_simplexml($article)->textContent;
    }
    

提交回复
热议问题