2

私はチェックし、多くの例で

following-sibling::text()[1]

強いタグの後にテキストを受け取るための正解として与えられます。興味のあるテキストをアスタリスクでマークしました。

    <?php
    $html='
      <html>
        <head>
        </head>
        <body>    
            <div class="someclass">
                <h2 class="h3">header 1</h2>
                <ul class="bulleted">
                    <li><strong>prop1: </strong>**name**</li>
                    <li><strong>prop2: </strong>**street**</li>
                    <li><strong>prop is 3: </strong>**city**</li>
                    <li><strong>prop 4: </strong>**more**</li>
                </ul>
            </div>
        </body>
    </html>
';
    $doc = new DOMDocument();
    $doc->strictErrorChecking = FALSE;
    $doc->loadHtml($html);
    $data = simplexml_import_dom($doc);
    $properties = $data->xpath('//strong/following-sibling::text()[1]');

    var_dump($properties);

私がいつも得るのは [strong] の内容ですが、[strong] の内容のない [li] [/li] 内のテキストではありません:

array(4) {
  [0] =>
  class SimpleXMLElement#3 (1) {
    public $strong =>
    string(7) "prop1: "
  }
  [1] =>
  class SimpleXMLElement#4 (1) {
    public $strong =>
    string(7) "prop2: "
  }
  [2] =>
  class SimpleXMLElement#5 (1) {
    public $strong =>
    string(11) "prop is 3: "
  }
  [3] =>
  class SimpleXMLElement#6 (1) {
    public $strong =>
    string(8) "prop 4: "
  }
}

エラー箇所を教えていただけると嬉しいです...

4

1 に答える 1

4

この XPath 操作には SimpleXML を使用しないでください。いくつかの点で制限があります。この場合、SimpleXML Xpath でテキスト ノードを返すことができないという制限があります。DOMXPathははるかに機能的で、テキスト ノードを含むすべてのノード タイプを返すことができます。

$xpath = new DOMXpath($doc);
$properties = $xpath->query('//strong/following-sibling::text()[1]');

foreach ($properties as $property)
  var_dump($property->textContent);

結果:

string(8) "**name**"
string(10) "**street**"
string(8) "**city**"
string(8) "**more**"
于 2013-04-03T00:07:27.227 に答える